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;
    }
}
相关推荐
adore.9681 分钟前
2.24 oj95 96 97
开发语言·c++·算法
白中白121383 分钟前
算法题-16
算法
梦帮科技5 分钟前
【DREAMVFIA开源】量子互联网协议:节点通信与路由算法
人工智能·神经网络·算法·生成对抗网络·开源·量子计算
cui_ruicheng7 分钟前
C++ 多态详解(上):概念与语言机制
开发语言·c++
fpcc9 分钟前
并行编程实战——CUDA编程的其它Warp函数
c++·cuda
菜鸡儿齐9 分钟前
leetcode-搜索插入位置
数据结构·算法·leetcode
52Hz11811 分钟前
力扣394.字符串解码、739.每日温度、84.柱状图中最大的矩形
python·算法·leetcode
hope_wisdom12 分钟前
C/C++数据结构之用链表实现队列
c语言·数据结构·c++·链表·队列
网小鱼的学习笔记14 分钟前
leetcode203移除链表元素
数据结构·链表
Yzzz-F15 分钟前
牛客寒假算法训练营4
算法