Monday 13 April 2009

PROJECT EULER #46

Link to Project Euler problem 46

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 + 2x12
15 = 7 + 2x22
21 = 3 + 2x32
25 = 7 + 2x32
27 = 19 + 2x22
33 = 31 + 2x12

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?


using System;

namespace project_euler
{
class Program
{
static void Main()
{
//Problem 46
DateTime start = DateTime.Now;
bool test=false;
for (int i = 3; i < 1000000; i++)
{
if (!IsPrime(i) && i % 2 != 0)
{
for (int j = 1; j <= i - 2; j += 2)
{
if (IsPrime(j))
{
test = false;
double k = i - j;
if (k % 2 == 0)
{
k = k / 2;
if (Math.Sqrt(k) == Math.Floor(Math.Sqrt(k)))
{
test = true;
break;
}
}
}
}
if (!test)
{
Console.WriteLine(i);
break;
}
}
}
TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
public static bool IsPrime(int n)
{
if (n < 2)
return false;
if (n == 2)
return true;
for (long i = 2; i <= Math.Sqrt(n); i++)
if (n % i == 0)
return false;
return true;
}
}
}
Triple-click for answer: 5777

No comments: