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;
    }
}
相关推荐
Snow_day.10 分钟前
有关平衡树
数据结构·算法·贪心算法·动态规划·图论
Hcoco_me27 分钟前
大模型面试题75:讲解一下GRPO的数据回放
人工智能·深度学习·算法·机器学习·vllm
Xの哲學31 分钟前
Linux设备驱动模型深度解剖: 从设计哲学到实战演练
linux·服务器·网络·算法·边缘计算
明洞日记1 小时前
【CUDA手册002】CUDA 基础执行模型:写出第一个正确的 Kernel
c++·图像处理·算法·ai·图形渲染·gpu·cuda
mikelv011 小时前
实现返回树状结构小记
java·数据结构
企业对冲系统官1 小时前
基差风险管理系统集成说明与接口规范
大数据·运维·python·算法·区块链·github
程序员-King.1 小时前
day134—快慢指针—环形链表(LeetCode-141)
算法·leetcode·链表·快慢指针
Swift社区1 小时前
LeetCode 376 摆动序列
算法·leetcode·职场和发展
oioihoii1 小时前
程序员如何系统入门Vibe Coding?
c++
高洁012 小时前
AIGC技术与进展(1)
深度学习·算法·机器学习·transformer·知识图谱