Primes Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 796 Accepted Submission(s): 368
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
找到小于10000的素数,用素数筛选法。
避开三重循环,采用二重循环,如果存在p3满足条件,则必定会有p3 = n - p1 - p2,如果p3是素数并且p3大于等于p2,则计数器加一。
因为使用三重循环直接查找,到时TLE了一回。。。。。。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int su[10000] = {2,3,5};
int prim[10000];
int init()
{
memset(prim,0,sizeof(prim));
prim[2] = 1;
prim[3] = 1;
prim[5] = 1;
int i,j,k,m = 2,bj;
k = 3;
for(i = 7; i <= 10000; i = i + m)
{
bj = 1;
m = 6 - m;
for(j = 0; su[j]*su[j] <= i; j++)
{
if(i%su[j] == 0)
{
bj = 0;
break;
}
}
if(bj == 1)
{
su[k++] = i;
prim[i] = 1;
}
}
return k;
}
int main()
{
int t,i,j,m;
int k = init();
while(~scanf("%d",&t))
{
int num = 0;
for(i = 0; i < k; i++)
{
for(j = i; j < k; j++)
{
m = t - su[i] - su[j];
if(m < 0)
{
break;
}
if(prim[m] == 1 && m >= su[j])
num++;
}
}
printf("%d\n",num);
}
return 0;
}