Twin Prime Conjecture
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1898 Accepted Submission(s): 592
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.
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
5
20
-2
Sample Output
0
1
4
1
4
Source
题意:
题目意思很简单就是判断孪生素数(遗憾的是本人英语是烂的一笔,刚开始居然没理解,啊!!!!!!).
之后就看你当时的脑神经如何的运转了,如果平时就喜欢暴力的话。那Ok这题就很简单,直接打表轻松过。
但是不知道是不是有某些会读研读傻了,会不会总是认为什么题都要高级算法的话。。。。 哈哈。开玩笑。。。。。
言归正传,如果要用算法的话,其实就是一个普通的树状数组简单题。
下面就给出两种不同的解法吧。
偷偷告诉你本人感觉用树状数组写是有点脑残的行为。。。。。简单的题目为何在研究生眼里就变得如此复杂呢????哈哈哈
素数刷选法:
#include <stdio.h>
#include <string.h> const int MAX = 100000 + 10;
bool prime[MAX];
int r[MAX]; void IsPrime()
{
memset(prime,0,sizeof(prime));
prime[0] = prime[1] = 1;
for(int i = 2;i < MAX;i++)
for(int j = 2;i*j < MAX;j++)
prime[j*i] = 1;
} void sove()
{
IsPrime();
r[0] = r[1] = r[2] = 0;
for(int i = 3;i < MAX;i++)
{
if(!prime[i-2]&&!prime[i])
r[i] = r[i-1] + 1;
else
r[i] = r[i-1];
}
}
int main()
{
int n;
sove();
while(scanf("%d",&n),n>-1)
{
printf("%d\n",r[n]);
}
return 0;
}
高级的树状素组法:
#include <iostream>
#define lowbit(t)(-t&t)
using namespace std ; const int MAX = 100001;
int prime[MAX],tree[MAX],num[MAX];
void update(int x,int val)
{
for(int i = x;i < MAX;i += lowbit(i))
tree[i] += val;
}
int GetSum(int x)
{
int sum=0;
for(int i = x;i > 0;i -= lowbit(i))
sum += tree[i];
return sum;
}
int main()
{
int cnt=0;
for(int i=2;i<MAX;i++) if(!prime[i])
{
num[cnt++]=i;
for(int j=i;i<318&&j*i<MAX;j++)
prime[i*j]=1;
}
for(int i=1;i<cnt;i++)
if(num[i]-num[i-1]==2)
update(num[i],1);
int n;
while(cin>>n,n>=0)
{
if(!n) cout<<"0"<<endl;
else cout<<GetSum(n)<<endl;
}
return 0;
}