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 分钟前
二叉树专题(下)
算法·深度优先
故事和你914 分钟前
洛谷-数据结构2-1-二叉堆与树状数组1
开发语言·数据结构·c++·算法·动态规划·图论
hhb_61813 分钟前
C语言核心技术难点梳理与实战案例解析
c语言·开发语言
海参崴-16 分钟前
C++ STL篇 红黑树的模拟实现
开发语言·c++
研究点啥好呢25 分钟前
Momenta后端开发面试题精选:10道高频考题+答案解析(数据产线方向)
c++·python·面试·求职招聘
多加点辣也没关系38 分钟前
数据结构与算法|第十七章:贪心算法
数据结构·算法·贪心算法
多加点辣也没关系39 分钟前
数据结构与算法|第十四章:排序算法(上)— 比较类排序
数据结构·算法·排序算法
Hical611 小时前
C++26 前瞻心得:下一代 C++ 最值得期待的特性
c++
悲伤小伞1 小时前
Linux_传输层协议TCP详解
linux·网络·c++·网络协议·tcp/ip
笨笨饿1 小时前
#72_聊聊I2C以及他们的变体
linux·c语言·网络·stm32·单片机·算法·个人开发