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;
    }
}
相关推荐
八个程序员3 分钟前
c++——探讨a÷b(long long)
开发语言·c++
77wpa3 分钟前
VS Code(Visual Studio Code)开发调试 C/C++ 工程配置
c++·vscode
bxlj_jcj14 分钟前
分布式ID方案、雪花算法与时钟回拨问题
分布式·算法
墨染点香15 分钟前
LeetCode 刷题【179. 最大数】
算法·leetcode·职场和发展
失忆已成习惯.19 分钟前
西农数据结构第四次实习题目参考
数据结构·算法·图论
kyle~19 分钟前
排序---堆排序(Heap Sort)
数据结构·c++·算法
yesyesido26 分钟前
3D在线魔方模拟器
科技·算法·3d·生活·业界资讯·交友·帅哥
王老师青少年编程26 分钟前
线性DP第12课:线性DP应用案例实践:数字三角形
c++·动态规划·dp·线性dp·csp·信奥赛·数字三角形
是苏浙30 分钟前
蓝桥杯备战day1
算法
汉克老师31 分钟前
CCF-NOI2025第一试题目与解析(第二题、序列变换(sequence))
c++·算法·动态规划·noi