Primes Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2829 Accepted Submission(s): 1268
Problem Description
Given a number n, please count how many tuple(p1, p2, p3) satisfied that p1<=p2<=p3, p1,p2,p3 are primes and p1 + p2 + p3 = n.
Input
Multiple test cases(less than 100), for each test case, the only line indicates the positive integer
n(n≤10000)
.
Output
For each test case, print the number of ways.
Sample Input
3 9
Sample Output
0 2
Source
Recommend
第一种利用三重循环,直接枚举。各种超时,。。。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[10000],b[110000];
void init()
{
int i,j,k=1;
a[0]=2;
for(i=3;i<10000;i++)
{
for(j=2;j*j<=i;j++)
if(i%j==0)
break;
if(j*j>i)
a[k++]=i;
}
}
void ac()
{
int i,j,k;
init();
memset(b,0,sizeof(b));
for(i=0;i<470;i++)
{
for(j=i;j<800;j++)
{
if(a[i]+a[j]>=10000)
break;
for(k=j;k<1229;k++)//最大的数据量1229.
{
b[a[i]+a[j]+a[k]]+=1;
}
}
}
}
int main()
{
int n;
ac();
while(scanf("%d",&n)!=EOF)
{
printf("%d\n",b[n]);
}
return 0;
}
利用二重循环远比三重循环好,所以以后尽量能用二重循环的不要用三重
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[11000],i,j,k,l,m,n,prime[10000];
void init()
{
memset(prime,1,sizeof(prime));
for(i=3;i<10000;i++)
{
for(k=2;k*k<=i;k++)
if((i%k==0))
{
prime[i]=0;
break;
}
}
}
int main()
{
init();
int n,i,j,k,count;
while(scanf("%d",&n)!=EOF)
{
count=0;
for(i=2;i<=n;i++)
for(j=i;j<=(n-i)/2;j++)
if(prime[i]&&prime[j]&&prime[n-i-j])
count++;
printf("%d\n",count);
}
return 0;
}