According to the Goldbach's Conjecture, every even number that is not less than 4 is the sum of two primes. So we can just reduce the number to an even number by subtracting 4=2+2 or 5=2+3 from it, and then test every possible summation of the remaining two addend to see if they are both primes.
Code:
- /***************************************************************************
- * Copyright (C) 2008 by Liu Kaipeng *
- * LiuKaipeng at gmail dot com *
- ***************************************************************************/
- /* @JUDGE_ID 00000 10168 C++ "Summation of Four Primes" */
- #include <algorithm>
- #include <cstdio>
- #include <cstring>
- #include <deque>
- #include <fstream>
- #include <iostream>
- #include <list>
- #include <map>
- #include <queue>
- #include <set>
- #include <stack>
- #include <string>
- #include <vector>
- using namespace std;
- int const max_primes = 10000001;
- bool primes[max_primes];
- void gen_primes()
- {
- primes[0] = primes[1] = false;
- for (int i = 2; i < max_primes; ++i)
- primes[i] = true;
- for (int i = 2; i < max_primes; ++i) {
- for (; i < max_primes && !primes[i]; ++i) {}
- for (int j = 2; i*j < max_primes; ++j)
- primes[i*j] = false;
- }
- }
- bool sum_primes(int n, int s[])
- {
- if (n < 8) return false;
- if (n % 2 == 0) {
- s[0] = s[1] = 2;
- n -= 4;
- } else {
- s[0] = 2;
- s[1] = 3;
- n -= 5;
- }
- for (int i = 2, e = n / 2; i <= e; ++i)
- if (primes[i] && primes[n-i]) {
- s[2] = i;
- s[3] = n - i;
- return true;
- }
- return false;
- }
- int main(int argc, char *argv[])
- {
- #ifndef ONLINE_JUDGE
- freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
- freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
- #endif
- gen_primes();
- char delim[] = " /n";
- for (int n, s[4]; cin >> n; )
- if (sum_primes(n, s))
- for (int i = 0; i < 4; ++i)
- cout << s[i] << delim[i];
- else
- cout << "Impossible./n";
- return 0;
- }