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 分钟前
算法设计与分析-习题8.2
数据结构·算法·排序算法·dfs·化简
玛卡巴卡ldf11 分钟前
【LeetCode 手撕算法】(子串) 560-和为 K 的子数组
java·数据结构·算法·leetcode
CoovallyAIHub20 分钟前
BMW GenAI4Q:每57秒下线一辆车,AI如何为每辆车定制专属质检清单
数据库·算法·架构
无限进步_22 分钟前
深入解析list:一个完整的C++双向链表实现
开发语言·c++·git·链表·github·list·visual studio
不想看见40423 分钟前
Rotate Image数组--力扣101算法题解笔记
数据结构·算法
仰泳的熊猫29 分钟前
题目 2304: 蓝桥杯2019年第十届省赛真题-特别数的和
数据结构·c++·算法·蓝桥杯
靠沿38 分钟前
【优选算法】专题十五——BFS解决FloodFill算法
算法·宽度优先
Bruce_kaizy42 分钟前
c++ linux环境编程——linux信号(signal)
linux·c++·操作系统·环境编程
2401_8496448544 分钟前
C++代码重构实战
开发语言·c++·算法
fengfuyao98544 分钟前
一个改进的MATLAB CVA(Change Vector Analysis)变化检测程序
前端·算法·matlab