Austin Hyde
Austin Hyde

Reputation: 27446

Sum of primes, Conundrum

So after pulling my hair out for 30 minutes, I have decided to come to SO for some help on this problem:

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 is wrong.

Any ideas?

Upvotes: 0

Views: 566

Answers (4)

Amos
Amos

Reputation: 1060

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

Upvotes: 0

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

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

Upvotes: 1

bm212
bm212

Reputation: 1439

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

Upvotes: 1

Amber
Amber

Reputation: 527063

        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?

Upvotes: 1

Related Questions