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 小时前
什么是ZCode for GLM-5.2?
开发语言·人工智能·python·科技·算法·ai编程·ai写作
长不胖的路人甲11 小时前
什么是赫夫曼树(哈夫曼树 / Huffman Tree)
python·算法·霍夫曼树
choumin11 小时前
创建型模式——原型模式
c++·设计模式·原型模式·创建型模式
三十岁老牛再出发12 小时前
07.26每日总结
linux·c语言·mysql
code_pgf12 小时前
C/C++ 常用容器功能汇总
c语言·开发语言·c++
Warren2Lynch12 小时前
掌握 UML 构造型、标记定义与标记值:面向领域特定建模的 UML 扩展全面指南
大数据·算法·uml
个 人 练 习 生12 小时前
strcmp与strstr函数的模拟实现
c语言·开发语言·经验分享·学习·程序人生
1570925113412 小时前
【无标题】
开发语言·python·算法
稚南城才子,乌衣巷风流12 小时前
换根法(Rerooting)算法详解
算法
小羊先生car13 小时前
RTOS-F429-HAL-基础内容认识(2026/7/26)
c语言