views:

138

answers:

3

So, I'm attempting to solve Project Euler Problem 10 in Java, and I'm getting not the right answer. Here's my code:

public class Problem10 {
public static void main(String[] args)
{
    long sum =0;
    for(int i =3;i<2000000;i+=2)
    {
        if(isPrime(i))
        {
            sum+=i;
        }
    }
    System.out.println(sum);
}

public static boolean isPrime(int n)
{
    boolean prime = true;
    if (n<2) return false;
    if (n==2) return true;
    if (n%2==0) return false;
    for (int i = 3; i<=Math.sqrt(n);i+=2)
    {
        if (n%i==0)
        {
            prime=false;
            break;
        }
    }
    return prime;
}
}

Which prints out 142913828920, which project Euler tells me is wrong.

Any ideas?

(Also, I know my method for finding primes is terribly inefficient.)

+1  A: 
for(int i =3;i<2000000;i+=2)

2 is prime.

dcp
If you'll notice above that, I have if (n==2) return true;
Colin DeClue
But in main, your loop starts at 3.
dcp
But you start at 3, so n will never equal 2
chris
Wow, I feel dumb. Thanks.
Colin DeClue
Just set sum = 2.
Will
+1  A: 

Hey man. You can accelerate your code a little bit by only dividing the prime numbers. For example, you can know that 35 is not a prime number by just trying to divide it by 2, 3, 5. No need to try 4. The trick is, any time you find a prime number, save it in a list or a vector. And in your isPrime function, just iterate the list until it hits sqrt(n) instead of every value in between 3..sqrt(n).

Good luck

dgg32
this would take a lot of memory
Amir Rachum
@amir: not really... there are < 150000 primes under 2 million, and they get more and more sparse as you get higher. using a list of 32 bit ints, that would only need 600kb.
Wallacoloo
In any case, the code takes less than 5 seconds to run as is. No need to optimize, really.
Colin DeClue
A: 

You can accelerate your code even more by using a Sieve.

Kizaru