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;
    }
}
相关推荐
生成论实验室27 分钟前
《事件关系阴阳博弈动力学:识势应势之道》第十一篇:双脑协同——WOLM与大模型的共生智能
人工智能·算法·语言模型·架构·创业创新
上弦月-编程1 小时前
高效编程利器:转移表技术解析
c语言·开发语言·数据结构·算法·排序算法
薇茗1 小时前
【初阶数据结构】 左右逢源的分支诗律 二叉树2
c语言·数据结构·算法·二叉树
AZaLEan__1 小时前
算法考核题解
算法
MediaTea1 小时前
AI 术语通俗词典:ID3 算法
人工智能·算法
Morwit1 小时前
【力扣hot100】 221. 最大正方形
前端·算法·leetcode
呃呃本1 小时前
算法题(矩阵)
线性代数·算法·矩阵
2301_789015621 小时前
Linux基础指令(一)
linux·运维·服务器·c语言·开发语言·c++·linux指令
呃呃本1 小时前
算法题(普通数组、矩阵)
线性代数·算法·矩阵
计算机安禾2 小时前
【计算机网络】第11篇:链路状态路由协议——Dijkstra算法与OSPF的分区架构
计算机网络·算法·架构