1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include <iostream>
using namespace std;
int get_primes(int array[], int num);
void sieve(int array[], int num);
void goldbach(int primes[], int nprimes, int num);
void show(int array[], int num);
int main()
{
int num;
cout << "Enter a number to calculate up to." << endl;
cin>>num;
if ( num < 2 )
return 0;
int array[num];
array[0]= array[1]= 0;
for ( int i= 2; i < num; ++i )
array[i]= i;
int nprimes = get_primes(array, num);
cout << nprimes << " found: ";
show(array, nprimes);
goldbach(array, nprimes, num);
return 0;
}
void show(int array[], int num)
{
for (int i=0; i<num; i++)
if (array[i] > 0)
cout << array[i] << " ";
cout << endl;
}
int get_primes(int array[], int num)
{
// identify primes
sieve(array, num);
// place them in a contiguous list
int pos = 0;
for (int i = 2; i < num; ++i)
if (array[i] > 0)
array[pos++] = array[i];
return pos;
}
void sieve( int array[], int num )
{
for ( int i= 0; i < num; ++i )
{
if ( array[i] > 0 )
{
for ( int j = i+i; j < num; j += i )
{
array[j] = 0;
}
}
}
}
// http://en.wikipedia.org/wiki/Goldbach%27s_conjecture
// Every integer greater than 5 can be written as the sum of three primes.
void goldbach(int primes[], int nprimes, int num)
{
// for each number in the range [6 .. num)
for (int n = 6; n < num; ++n)
{
bool found = false;
int i, j, k;
// look for 3 primes that match n
for (i = 0; !found && i < nprimes && primes[i] < n/2; ++i)
for (j = 0; !found && j < nprimes && primes[i] < n/2; ++j)
for (k = 0; !found && k < nprimes && primes[i] < n/2; ++k)
{
found = n == (primes[i] + primes[j] + primes[k]);
if (found)
cout << n << '\t' << primes[i] << " + " << primes[j] << " + " << primes[k] << endl;
}
if (!found)
cout << n << "\tnot found" << endl;
}
}
|