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;
    }
}
相关推荐
foundbug9994 分钟前
Modbus协议C语言实现(易于移植版本)
java·c语言·前端
Luna-player5 分钟前
在前端中list.map的用法
前端·数据结构·list
Herbert_hwt19 分钟前
C语言字符输入输出函数全解:从基础到实战应用
c语言
历程里程碑22 分钟前
C++ 10 模板进阶:参数特化与分离编译解析
c语言·开发语言·数据结构·c++·算法
老秦包你会28 分钟前
C++进阶------智能指针和特殊类设计方式
开发语言·c++
星辞树1 小时前
从 In-context Learning 到 RLHF:大语言模型的范式跃迁
算法
再__努力1点1 小时前
【68】颜色直方图详解与Python实现
开发语言·图像处理·人工智能·python·算法·计算机视觉
mingchen_peng1 小时前
第一章 初识智能体
算法
code bean1 小时前
【CMake 】[第十篇]CMake find_package 完全指南:让第三方库集成变得简单
c++·cmake
百锦再1 小时前
国产数据库的平替亮点——关系型数据库架构适配
android·java·前端·数据库·sql·算法·数据库架构