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;
    }
}
相关推荐
马士兵教育2 分钟前
2026年IT行业基本预测!计算机专业学生就业编程语言Java/C/C++/Python该如何选择?
java·开发语言·c++·人工智能·python·面试·职场和发展
Σίσυφος19003 分钟前
周期 Pattern Removal 算法
算法
飞Link6 分钟前
深度捕捉时序本质:TSTD 异常检测之表示学习(Representation-based)全解析
学习·算法·数据挖掘·回归
Book思议-10 分钟前
顺序表和链表核心差异与优缺点详解
java·数据结构·链表
滴滴答滴答答14 分钟前
机考刷题之 10 LeetCode 200 岛屿数量
算法·leetcode·职场和发展
梦游钓鱼1 小时前
Logger.h和Logger.cc文件分析
开发语言·c++
mit6.8241 小时前
Agent memory发展路线
算法
青桔柠薯片1 小时前
Linux I/O多路复用:深入浅出poll与epoll
linux·运维·服务器·算法
REDcker1 小时前
Linux C++ 内存泄漏排查分析手册
java·linux·c++
临溟夜空的繁星2 小时前
C++ STL-- vector
开发语言·c++