So after pulling my hair out for 30 minutes, I have decided to come to SO for some help on Project Euler #10:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Now, I don't want to know how to do the problem - that's easy - and especially not the answer. I would like to know why my code isn't giving me the correct answer when I run it (C#):
using System;
using System.Collections.Generic;
public class Euler010 {
public static bool isPrime(Int64 n) {
if (n <= 1)
return false;
if (n < 4)
return true;
if (n % 2 == 0)
return false;
if (n < 9)
return true;
if (n % 3 == 0)
return false;
Int64 r = (Int64)Math.Floor(Math.Sqrt((double)n));
Int64 f = 5;
while (f <= 4) {
if (n % f == 0)
return false;
if (n % (f + 2) == 0)
return false;
f += 6;
}
return true;
}
public static void Main() {
Int64 sum = 2;
for (Int64 n = 3; n <= 2000000; n+=2) {
if (isPrime(n)) {
sum += n;
}
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
When run to n <= 10
, it outputs 17
, like it should. When run to anything that's easy to compute by hand, it outputs the correct answer (like n <= 20
-> 77
).
However, when I run this, it outputs 666667333337
which Project Euler says is wrong.
Any ideas?