开发者

Project Euler #10, java [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Project Euler, Problem 10 java solution not working

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 tel开发者_开发问答ls me is wrong.

Any ideas?

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


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

2 is prime.


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).


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


I found the following method very efficient , when i checked if a number is prime i only divide the number by the prime numbers previously found and are below square root of n . No need to check for all the numbers below square root of n . And it only takes more than one second !!

public class Problem10 {

    private static List<Long> listOfPrimes = new ArrayList<Long>();

    public static void main(String args[]) {

        long count = 0;
        for (long i = 2; i < 2000000; i++) {
            if (isPrime(i)) {
                count += i;
                System.out.print(i + " ");
            }
            if (i % 1000 == 0) {
                System.out.println();
            }
        }

        System.out.println("\nTotal " + count);

    }

    private static boolean isPrime(long n) {

        String strFromN = new Long(n).toString();
        if ((strFromN.length() != 1) && (strFromN.endsWith("2") || strFromN.endsWith("4") || strFromN.endsWith("5") || strFromN.endsWith("6") || strFromN.endsWith("8"))) {
            return false;
        }

        for (Long num : listOfPrimes) {
            if (num > Math.sqrt(n)) {
                break;
            }
            if (n % num.longValue() == 0) {
                return false;
            }
        }


        listOfPrimes.add(new Long(n));
        return true;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜