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;
    }
}
相关推荐
m0_748250034 分钟前
C++ 官方文档与标准
开发语言·c++
漫随流水23 分钟前
leetcode算法(104.二叉树的最大深度)
数据结构·算法·leetcode·二叉树
matlabgoodboy29 分钟前
程序代做python代编程matlab定制代码编写C++代写plc设计java帮做
c++·python·matlab
机器学习之心HML37 分钟前
鲸鱼算法(WOA)优化Kriging模型
算法
DYS_房东的猫1 小时前
《 C++ 零基础入门教程》第6章:模板与 STL 算法 —— 写一次,用万次
开发语言·c++·算法
Tim_101 小时前
【算法专题训练】37、前缀树&二叉树
算法
点云SLAM1 小时前
C++ 静态初始化顺序问题(SIOF)和SLAM / ROS 工程实战问题
开发语言·c++·slam·静态初始化顺序问题·工程实战技术·c++static 关键字
NineData1 小时前
第三届数据库编程大赛-八强决赛成绩揭晓
数据库·算法·代码规范
雍凉明月夜1 小时前
深度学习之目标检测yolo算法Ⅱ(v4)
深度学习·算法·yolo·目标检测
pen-ai1 小时前
打通 Python 与 C++ 的参数传递机制
开发语言·c++·python