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;
    }
}
相关推荐
罗湖老棍子几秒前
A Horrible Poem(信息学奥赛一本通- P1460) [POI 2012] OKR-A Horrible Poem(洛谷-P3538)
算法·哈希·欧拉筛·错位重叠
程序员爱德华7 分钟前
LeetCode刷题
算法·leetcode
memcpy07 分钟前
LeetCode 1202. 交换字符串中的元素【无向图连通分量】中等
算法·leetcode·职场和发展
AI人工智能+电脑小能手7 分钟前
【大白话说Java面试题】【Java基础篇】第5题:HashMap的底层原理是什么
java·开发语言·数据结构·后端·面试·hash-index·hash
小成202303202658 分钟前
数据结构(整理常见结构总结到树层级)
java·c语言·数据结构·c++·链表
ximu_polaris9 分钟前
设计模式(C++)-结构型模式-外观模式
c++·设计模式·外观模式
fengfuyao98510 分钟前
基于遗传算法的分布式电源选址定容优化(考虑环境因素)
算法·matlab·平面
睡觉就不困鸭11 分钟前
第10天 删除有序数组中的重复项
数据结构·算法
Chase_______15 分钟前
LeetCode 643:子数组最大平均数 I
算法·leetcode
Xiu Yan18 分钟前
Java 转 C++ 系列:STL常用函数
java·开发语言·c++·stl·visual studio