Bookmark and Share

free counters
Back to the Training Home

Lesson: 9
Problem: 543
Title: Goldbach's Conjecture
Difficulty Level: 2
Date: Dec 17, 2008
Site: UVA

Solution:
Few first prime numbers are: 3 5 7 11 13 17 19 23 29 31 37....
Let input is 20. Take two indexs, first one will points the first prime number and other will point the last one as well.
Say int index_1 = 0 (assume prime numbers are stored in an array, and 0 is the first index as you know)
int index_2 = 10 ( as an example, which hold 37 as mentioned above)

Follow this procedure:
int sum = Prime[index_1] + Prime[index_2]; ( lets Prime is an array which holds the prime numbers)
if sum > 20 ( 20 is our input), then index_2 --;
if sum < 20 then index_1 ++;
if sum == 20, then index_2 --, and save the result.

Repeat this process till index_1 <= index_2 and every time update the result you if get.

Code:

void getResult(int n) {
int index_1 = 0, sum;
int index_2 = last_index; ( last_index means the last index of the Prime array)
int res_1, res_2;
while(index_1 <= index_2) {
sum = Prime[index_1] + Prime[index_2];
if(sum > n) index_2--;
if(sum < n) index_1 ++;
if(sum == n) {
res_1 = Prime[index_1];
res_2 = Prime[index_2];
index_2--;
}
}
printf("%d = %d + %d\n",n,res_1,res_2);

I think there is no such case where you have to print Goldbach's conjecture is wrong.

To solve this problem, you first have to know how to generate prime numbers.
If are you not to familiar, please visit my algorithm source codes section where i implements sieve of Eratosthenes to generate prime number quickly. Title: 'Generating Prime Numbers'

Back to the Training Home