Algorithm


problem Link : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1109

Euler proved in one of his classic theorems that prime numbers are infinite in number. But can every number be expressed as a summation of four positive primes? I don’t know the answer. May be you can help!!! I want your solution to be very efficient as I have a 386 machine at home. But the time limit specified above is for a Pentium III 800 machine. The definition of prime number for this problem is “A prime number is a positive number which has exactly two distinct integer factors”. As for example 37 is prime as it has exactly two distinct integer factors 37 and 1. Input The input contains one integer number N (N ≤ 10000000) in every line. This is the number you will have to express as a summation of four primes. Input is terminated by end of file. Output For each line of input there is one line of output, which contains four prime numbers according to the given condition. If the number cannot be expressed as a summation of four prime numbers print the line ‘Impossible.’ in a single line. There can be multiple solutions. Any good solution will be accepted.

Sample Input 24 36 46

Sample Output 3 11 3 7 3 7 13 13 11 11 17 7

Code Examples

#1 Code Example with C Programming

Code - C Programming

 #include <bits/stdc++.h>
using namespace std;
int fastio() { ios_base::sync_with_stdio(false); cout << fixed << setprecision(10); cin.tie(nullptr); return 0; }

int __fastio = fastio();

constexpr int N = 10000001;
bitset < N> isprime;
vector<int> primes;
void sieve() {
	isprime.set();
	isprime[0] = isprime[1] = false;
	for(ll i=2;i < N;i++) {
		if(!isprime[i]) continue;
		primes.push_back(i);
		for(ll j=i*i;j<N;j+=i) isprime[j] = false;
	}
}

void solve() {
	ll x;
	sieve();
	while(cin >> x) {
		if(x < 8> {
			cout << "Impossible.\n";
		} else {
			// Goldbach's conjecture, every even number >= 4 can be represented as two prime
			cout << 2 << " ";
			cout << (x%2 ? 3 : 2) << " ";
			x -= 4 + (x%2); // make even

			for(int y : primes) {
				if(isprime[x-y]) {
					cout << y << " " << x-y << "\n";
					break;
				}
			}
		}
	}
}

int main() {
    int t=1;
    while(t--) {
        solve();
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
24
36
46

Output

x
+
cmd
3 11 3 7
3 7 13 13
11 11 17 7
Advertisements

Demonstration


UVA Online Judge solution - 10168 - Summation of Four Primes - UVA Online Judge solution in C,C++,Java         

Previous
UVA Online Judge solution - 10163-Storage Keepers - UVA Online Judge solution in C,C++,Java
Next
UVA Online Judge solution - 10171 - Meeting Prof Miguel - UVA Online Judge solution in C,C++,Java