Twin Prime Conjecture

一、题目

If we define dn as: dn = pn+1-pn, where pi is the i-th prime. It is easy to see that d1 = 1 and dn=even for n>1. Twin Prime Conjecture states that "There are infinite consecutive primes differing by 2".

Now given any positive integer N (< 10^5), you are supposed to count the number of twin primes which are no greater than N.

Input

Your program must read test cases from standard input.

The input file consists of several test cases. Each case occupies a line which contains one integer N. The input is finished by a negative N.

Output

For each test case, your program must output to standard output. Print in one line the number of twin primes which are no greater than N.

Sample

Inputcopy Outputcopy

1

5

20

-2

0

1

4

二、分析

预处理ans数组,最后输出只需要O(1)的复杂度

Twin Prime指的是相差为2 的素数

20以内的素数:

2 3 5 7 11 13 17 19

其中有以下4对Twin Prime:(2,5),(5,7),(11,13),(17,19)

cpp 复制代码
#include<iostream>
using namespace std;
const int N=1e5+5;
int a[N];
int ans[N];
int main()
{
    for(int i=2;i<=N/i;i++)
    {
        for(int j=i*i;j<N;j+=i)
        {
            a[j]=1;//表示不是素数
        }
    }
    int cnt=0;
    a[0]=1,a[1]=1;
    for(int i=2;i<=N;i++)
    {
        if(a[i]==0&&a[i-2]==0) cnt++;
        ans[i]=cnt;
    }
    int n;
    while(cin>>n&&n>=0)
    {
        cout<<ans[n]<<endl;
    }
}
相关推荐
hanbr9 小时前
C++ 初涉
开发语言·c++
Дерек的学习记录9 小时前
C++:入门基础(下)
开发语言·数据结构·c++·学习·算法·visualstudio
yugi9878389 小时前
无线传感器网络中GAF算法节点特性分析
网络·算法
1027lonikitave10 小时前
使用斐波那契数列讲解尾递归
算法
云深麋鹿10 小时前
标准库中的String类
开发语言·c++·容器
myron668811 小时前
基于STM32LXXX的模数转换芯片ADC(MCP3421A0T-E/CH)驱动C程序设计
c语言·stm32·嵌入式硬件
滴滴答滴答答11 小时前
LeetCode Hot100 之 16 合并两个有序链表
算法·leetcode·链表
ASKED_201911 小时前
企业级大模型微调(Fine-tuning)策略
大数据·人工智能·算法
t1987512811 小时前
基于Chirp分解和多相快速算法的离散分数傅里叶变换(DFRFT)MATLAB实现
开发语言·算法·matlab
愚者游世12 小时前
力扣解决二进制 | 题型常用知识点梳理
c++·程序人生·算法·leetcode·职场和发展