Project Euler Problem 46
阿新 • • 發佈:2018-11-02
Problem 46 : Goldbach’s other conjecture
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×12
15 = 7 + 2×22
21 = 3 + 2×32
25 = 7 + 2×32
27 = 19 + 2×22
33 = 31 + 2×12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
#include <iostream>
#include <vector>
#include <iterator>
#include <cmath>
using namespace std;
class PE0046
{
private:
static const int m_max = 1000000; // one million
bool checkPrime(int number);
bool validateGoldbachOtherConjecture(int number, vector<int>& primes_v);
public:
int findSmallestOddComposite();
};
bool PE0046::checkPrime(int number)
{
if (number%2 == 0 && number>2 || number < 2)
{
return false;
}
double squareRoot=sqrt((double)number);
for(int i=3;i<=(int)squareRoot;i+=2) // 3, 5, 7, ...(int)squareRoot
{
if (number % i == 0)
{
return false;
}
}
return true;
}
bool PE0046::validateGoldbachOtherConjecture(int number, vector<int>& primes_v)
{
vector<int>::reverse_iterator iter=primes_v.rbegin();
int prime;
int diff;
while (iter != primes_v.rend())
{
prime = *iter;
diff = number - prime;
if (0 == diff % 2)
{
int root = (int)sqrt((double)diff/2.0);
if (diff == 2*root*root) // number = prime + 2*root*root
{
#ifdef UNIT_TEST
cout << number << " = " << prime << " + 2 x "<<root<<"^2"<<endl;
#endif
return true;
}
}
iter++;
}
return false;
}
int PE0046::findSmallestOddComposite()
{
vector<int> primes_v;
for (int number=2; number<m_max; number++)
{
if(true == checkPrime(number))
{
primes_v.push_back(number);
}
else if (number%2 == 1) // odd composite
{
if (false == validateGoldbachOtherConjecture(number, primes_v))
{
return number;
}
}
}
return 0;
}
int main()
{
PE0046 pe0046;
cout << pe0046.findSmallestOddComposite() << " is the smallest odd composite ";
cout << "that cannot be written as the sum of a prime and twice a square."<<endl;
return 0;
}