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 分钟前
学习笔记——栈
开发语言·数据结构·笔记·学习·算法
自然语3 分钟前
人工智能之数字生命-情绪
人工智能·算法
qq_73917536910 分钟前
开源基于STC8的智能浇花与温湿度报警系统
c语言·stm32·单片机·嵌入式硬件
Ayanami_Reii12 分钟前
进阶数据结构应用-维护序列
数据结构·算法·线段树
_w_z_j_18 分钟前
mari和shiny() (多状态dp数组)
算法
GesLuck20 分钟前
Beaglebone BB Black C版 AM3358(一)
c语言·开发语言·物联网·硬件架构
CoderYanger22 分钟前
C.滑动窗口-越长越合法/求最短/最小——2904. 最短且字典序最小的美丽子字符串
java·开发语言·数据结构·算法·leetcode·1024程序员节
Tim_1024 分钟前
【算法专题训练】33、堆
算法
lijiatu1008629 分钟前
[C++] QTimer与Qt事件循环机制 实验探究
c++·qt
三月微暖寻春笋35 分钟前
【和春笋一起学C++】(四十九)C++中string类的简介
c++·cstring·string类·string类的实现·string类方法