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;
    }
}
相关推荐
搂鱼1145146 分钟前
一类判断包含颜色整体的题目
算法
Demon--hx8 分钟前
[c++]string的三种遍历方式
开发语言·c++·算法
无敌最俊朗@22 分钟前
力扣hot100 - 合并两个有序链表21
算法·leetcode·链表
墨染点香30 分钟前
LeetCode 刷题【168. Excel 表列名称】
算法·leetcode·职场和发展
hans汉斯36 分钟前
基于改进YOLOv11n的无人机红外目标检测算法
大数据·数据库·人工智能·算法·yolo·目标检测·无人机
理人综艺好会1 小时前
redis学习之基础数据结构
数据结构·redis·学习
星轨初途1 小时前
数据结构二叉树之链式结构(3)(下)
c语言·网络·数据结构·经验分享·笔记·后端
valan liya1 小时前
C++list
开发语言·数据结构·c++·list
Swift社区1 小时前
LeetCode 431 - 将 N 叉树编码成二叉树
算法·leetcode·职场和发展
小毅&Nora1 小时前
【后端】【C++】智能指针详解:从裸指针到 RAII 的优雅演进(附 5 个可运行示例)
c++·指针