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;
}
海岛Blog
发布了2106 篇原创文章 · 获赞 2299 · 访问量 253万+
关注