首页 > 代码库 > HDU-5104-Primes Problem (BestCoder Round #18!!)

HDU-5104-Primes Problem (BestCoder Round #18!!)

Primes Problem

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


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(n10000).
 

Output
For each test case, print the number of ways.
 

Sample Input
3 9
 

Sample Output
0 2
 

Source
BestCoder Round #18
 


简单水过~~

思路:首先将10000内的素数筛出来(约1000个),(p1,p2,p3)枚举三元组前两个p1,p2,可知若存在p3满足条件,必有p3=n?p1?p2,故令t=n?p1?p2。若t为不小于p2的素数,则t满足p3的条件。则答案加一。

AC代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;

int main()
{
	int n, prime[2000], pnum=0, isprime[10005];
	memset(isprime, 0, sizeof(isprime));
	for(int i=2; i<=10000; i++)
	{
		if(!isprime[i])
		{
			prime[pnum++] = i;
			for(int j = i<<1; j<=10000; j+=i)
				isprime[j] = 1;
		}
	} 
	/*for(int i=0; i<pnum; i++)
	{
		printf("%d ", prime[i]);
	}*/
	while(scanf("%d", &n)!=EOF)
	{
		int i, j, ans=0;
		for(i = 0; prime[i]<=n; i++)
		{
			for(j = i; prime[j]<=n; j++)
			{
				int t = n - prime[i] - prime[j];
				if(t>=prime[j] && isprime[t]==0)ans++;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
} 




HDU-5104-Primes Problem (BestCoder Round #18!!)