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;
    }
}
相关推荐
DolphinDB智臾科技13 小时前
DolphinDB 走进东南大学 | 新型电力系统高频数据处理与算法落地实战
算法
Zzzzmo_14 小时前
前缀和算法
算法·前缀和
睡觉就不困鸭14 小时前
第十八天 有效的括号
数据结构·算法
_日拱一卒14 小时前
LeetCode:148排序链表
算法·leetcode·链表
小小de风呀14 小时前
de风——【从零开始学C++】(三):类和对象(中序):默认成员函数全解析
开发语言·c++
cen__y14 小时前
Linux06(进程)
linux·运维·服务器·c语言·ubuntu
迷途之人不知返14 小时前
vector的模拟实现
c++
IpdataCloud14 小时前
IP查询工具的准确率怎么评估?一份可上生产的选型与验收指南
网络·人工智能·算法
生信研究猿14 小时前
leetcode 78.子集
算法·leetcode·深度优先
sycmancia14 小时前
Qt——文本编辑器中的功能交互
qt·算法