HDU3792 Twin Prime Conjecture【篩選法+前綴和】

Twin Prime Conjecture

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4300 Accepted Submission(s): 1652

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.

Sample Input
1
5
20
-2

Sample Output
0
1
4

Source
浙大計算機研究生保研複試上機考試-2011年

問題鏈接HDU3792 Twin Prime Conjecture
問題簡述:求n以內的孿生素數的對數,孿生素數即p和p+2都爲素數。
問題分析
    用篩選法先將N以內的素數標記出來,算出前綴和備用。
    算前綴和的邏輯放到篩選法函數中。
程序說明:(略)
參考鏈接:(略)
題記:(略)

AC的C++語言程序如下:

/* HDU3792 Twin Prime Conjecture */

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5;
const int SQRTN = sqrt((double) N);
bool isprime[N + 1];
int ps[N + 1];
// Eratosthenes篩選法
void esieve(void)
{
    memset(isprime, true, sizeof(isprime));

    isprime[0] = isprime[1] = false;
    for(int i = 2; i <= SQRTN; i++) {
        if(isprime[i]) {
            for(int j = i * i; j <= N; j += i)  //篩選
                isprime[j] = false;
        }
    }

    // 計算前綴和
    ps[0] = ps[1] = ps[2] = ps[3] = 0;
    for(int i = 4; i <= N; i++)
        if(isprime[i - 2] && isprime[i]) ps[i] = ps[i - 1] + 1;
        else ps[i] = ps[i -1];
 }

int main()
{
    esieve();

    int n;
    while(~scanf("%d", &n) && n >= 0)
        printf("%d\n", ps[n]);

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章