UVA10948 The primary problem【欧拉筛法+贪心】

Larry now lost most of his knowledge after spending a few years on deserted islands all over the place. When Ryan brought up the fact that every even number greater than 3 can represented as the sum of two prime numbers, he
couldn’t believe it! So now Larry is trying to come up with some kind of counterexample, and you can help him!
Input
Each line will contain an integer N greater than 3. The input will terminate when N is 0. N will not be bigger than 1 million.
Output
For each test case, output one way of summing two prime numbers. If there are more than one set of sums for which this is true, choose the set of sum the maximizes the difference between them. See the sample output. If a number cannot be represented as the sum of two prime number, print “NO WAY!” as below.
Note: 10 can be 3+7 or 5+5, and since 7-3 is bigger than 5-5, we choose 3+7.
Sample Input
4
5
6
7
9
10
11
0
Sample Output
4:
2+2
5:
2+3
6:
3+3
7:
2+5
9:
2+7
10:
3+7
11:
NO WAY!

问题链接UVA10948 The primary problem
问题简述:给定整数n>3,求两个素数使得它们的和为n,且差值最大。
问题分析
    使用筛法求得百万以内所有素数,然后顺序查找即可。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA10948 The primary problem */

#include <bits/stdc++.h>

using namespace std;

const int N = 1000000;
bool isprime[N + 1];
int prime[N / 3], pcnt = 0;
// 欧拉筛
void eulersieve(void)
{
    memset(isprime, true, sizeof(isprime));

    isprime[0] = isprime[1] = false;
    for(int i = 2; i <= N; i++) {
        if(isprime[i])
            prime[pcnt++] = i;
        for(int j = 0; j < pcnt && i * prime[j] <= N; j++) {  //筛选
            isprime[i * prime[j]] = false;
            if(i % prime[j] == 0) break;
        }
    }
 }

int main()
{
    eulersieve();

    int n;
    while(~scanf("%d", &n) && n) {
        int ans = 0;
        for(int i = 0; i < pcnt; i++) {
            if((prime[i] << 1) > n) break;
            if(isprime[n - prime[i]]) {
                ans = prime[i];
                break;
            }
        }

        if(ans) printf("%d:\n%d+%d\n", n, ans, n - ans);
        else printf("%d:\nNO WAY!\n",n);
    }

    return 0;
}
发布了2126 篇原创文章 · 获赞 2306 · 访问量 254万+

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/104543468