views:

208

answers:

4

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?

+1  A: 
        Int64 f = 5;
        while (f <= 4) {

Maybe I'm missing something here but these two lines don't seem to make sense. I'm fairly certain that the code posted above will never execute the body of the while loop.

Perhaps you meant to check if f is less than the square root of r?

Amber
DOH! Thanks for that. This is what happens with small keyboards...
Austin Hyde
+1  A: 

You're not using the variable r in your loop, I assume you probably want to loop while f<=r?

bm212
+1  A: 

Not what you are looking for, but you should probably use something like Sieve of Eratosthenes to generate your primes.

Soufiane Hassou
A: 

Plus the existing tests catch all non-primes below 20 (divisible by 2, 3, etc).

Amos