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;
    }
}
相关推荐
weixin_4130632112 小时前
比较阅读理解opencv 和 LuminanceHDR中 色调映射Drago算法
opencv·算法·计算机视觉·hdr·色调映射
自我意识的多元宇宙12 小时前
【数据结构】图----图的应用(拓扑排序)
数据结构·算法
Lazionr12 小时前
双向链表及链表篇总结
数据结构·链表
三品吉他手会点灯12 小时前
C语言学习笔记 - 16.C编程预备计算机专业知识 - Hello World程序的运行原理
c语言·笔记·学习
itzixiao12 小时前
L1-055 谁是赢家(10 分)[java][python]
java·python·算法
ghie909012 小时前
运用强跟踪无迹卡尔曼滤波来实现捷联惯导的初始对准
算法
菜菜的顾清寒12 小时前
力扣HOT100(21)相交链表
算法·leetcode·链表
zh路西法12 小时前
【ROS2多激光雷达融合】基于ROS2的双2D激光雷达点云融合与遮挡剔除方案
c++·python·机器人
七颗糖很甜12 小时前
开源雷达NEXRAD Level 3 数据完整获取与 Python 处理教程
大数据·python·算法
JXNL@12 小时前
TDK DPX105950DT 射频双工器全解析:从原理、参数到应用设计
算法