hdu3792题解

Problem Description
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.

分析:
这道题有的大佬用了树状数组避免超时(菜鸡不会了),我用了num数组维护,记录每一个数的孪生素数值
这道题一定要读懂再去做,注意题目的要求是寻找孪生素数
孪生素数a,b满足三个条件:
1.a为素数
2.b为素数
3.a,b相差为2
注意:2,3差为1,因此不是孪生素数
数可以重复利用,3,5 5,7均为孪生素数(5重复了)所以7的输 出应为2
因为数据范围原因,以及可能询问多次,用了num维护,和之前的思路差不多。。。

#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int vis[maxn],num[maxn],prime[maxn],k;
void E_sieve()
{
    int i,j;
    for(i=0;i<=maxn;i++)
    {
        vis[i]=1;
    }

    for(i=2;i*i<=maxn;i++)
    {
        if(vis[i])
        {
            for(j=i*i;j<=maxn;j+=i)
            {
                vis[j]=0;
            }
        }
    }

    for(i=2;i<=maxn;i++)
    {
        if(vis[i]) prime[k++]=i;
    }

    vis[1]=0;
    num[1]=0;
    num[2]=0;
    for(i=3;i<=maxn;i++)
    {
        if(vis[i]&&vis[i-2])
        {
            num[i]=num[i-1]+1;
        }
        else
        {
            num[i]=num[i-1];
        }
    }
}
int main()
{
    int a,i;
    E_sieve();
    while(cin>>a)
    {
        if(a<0) break;
        cout<<num[a]<<endl;

    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值