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;
    }
}
相关推荐
444A4E1 小时前
C++模板:泛型编程的魔法手册,从入门到“魔改”
c++·编译原理
ChiaWei Lee1 小时前
【C语言】深入理解指针(三):C语言中的高级指针应用
c语言·开发语言
最后一个bug1 小时前
教你快速理解linux中的NUMA节点探测是干什么用的?
linux·c语言·开发语言·arm开发·嵌入式硬件
trust Tomorrow1 小时前
每日一题-力扣-2278. 字母在字符串中的百分比 0331
算法·leetcode
Chiyamin1 小时前
C++面向对象速览(三)
c++
Tadecanlan1 小时前
[C++面试] 智能指针面试点(重点)续4
开发语言·c++·面试
Chiyamin1 小时前
C++面向对象速览(一)
c++
Lecea_L1 小时前
你能在K步内赚最多的钱吗?用Java解锁最大路径收益算法(含AI场景分析)
java·人工智能·算法
Tony881 小时前
热题100 - 394. 字符串解码
java·算法
GOTXX1 小时前
BoostSiteSeeker项目实战
前端·c++·后端·mysql·搜索引擎·项目实战·boost