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;
    }
}
相关推荐
一个不知名程序员www几秒前
算法学习入门--- set与map(C++)
c++·算法
鸿途优学-UU教育8 分钟前
法考命题趋势解读:为何越来越重视“实战能力”?
算法·法律·uu教育·法考机构
Rui_Freely10 分钟前
Vins-Fusion之 相机—IMU在线标定(两帧间旋转估计)(十)
人工智能·算法·计算机视觉
独自破碎E11 分钟前
链表中的节点每k个一组翻转
数据结构·链表
小此方25 分钟前
Re: 从零开始的C++ 入門(十)类和对象·最终篇下:类型转换、static成员、友元、匿名对象、内部类、拷贝编译优化
开发语言·c++·底层
mit6.82428 分钟前
二分猜答案
算法
王老师青少年编程28 分钟前
2025年12月GESP(C++)考级真题及详细题解(汇总版)
c++·题解·真题·gesp·csp·信奥赛·考级
_OP_CHEN39 分钟前
【算法基础篇】(四十二)数论之欧拉函数深度精讲:从互质到数论应用
c++·算法·蓝桥杯·数论·欧拉函数·算法竞赛·acm/icpc
CSDN_RTKLIB1 小时前
inline内联函数基础知识
开发语言·c++
Eloudy1 小时前
模板函数动态库与头文件设计示例
算法·cuda