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;
    }
}
相关推荐
啊吧怪不啊吧11 小时前
C++之基于正倒排索引的Boost搜索引擎项目usuallytool部分代码及详解
开发语言·c++·搜索引擎·项目
专注前端30年11 小时前
智能物流路径规划系统:核心算法实战详解
算法
json{shen:"jing"}12 小时前
字符串中的第一个唯一字符
算法·leetcode·职场和发展
java干货12 小时前
如何让 iPhone 用上 Type-C 充电器?适配器模式详解
c语言·iphone·适配器模式
追随者永远是胜利者12 小时前
(LeetCode-Hot100)15. 三数之和
java·算法·leetcode·职场和发展·go
代码改善世界13 小时前
C语言项目实战:学生成绩管理系统(支持登录注册、随机考试、分数区间统计)
c语言·网络·课程设计
程序员酥皮蛋13 小时前
hot 100 第二十七题 27.合并两个有序链表
数据结构·leetcode·链表
BlockWay13 小时前
西甲赛程搬进平台:WEEX以竞猜开启区域合作落地
大数据·人工智能·算法·安全
404未精通的狗14 小时前
(高阶数据结构)并查集
数据结构
漫雾_14 小时前
两个强制结束进程的方法
c++·驱动开发·安全