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;
    }
}
相关推荐
JiL 奥4 分钟前
Nexus制品归档(c/c++项目)
c语言·c++
j445566116 分钟前
C++中的职责链模式实战
开发语言·c++·算法
m0_6860416110 分钟前
实时数据流处理
开发语言·c++·算法
梵刹古音12 分钟前
【C语言】 字符型变量
c语言·开发语言·嵌入式
波波侠817 分钟前
代码随想录算法训练营打卡第31天|56. 合并区间、738.单调递增的数字
算法
Snow_day.18 分钟前
有关线段树应用(1)
数据结构·算法·贪心算法·动态规划·图论
知无不研23 分钟前
内存碎片与内存优化
开发语言·c++·内存优化·内存碎片·内存操作
m0_5613596726 分钟前
C++模块接口设计
开发语言·c++·算法
从此不归路34 分钟前
Qt5 进阶【11】图形视图框架:用 QGraphicsView 搭一个流程图编辑器
开发语言·c++·qt
wengqidaifeng1 小时前
探索数据结构(二):空间复杂度
c语言·开发语言·数据结构