Project Euler #10 Java solution not working

后端 未结 6 440
春和景丽
春和景丽 2020-12-12 00:01

I\'m trying to find the sum of the prime numbers < 2,000,000. This is my solution in Java but I can\'t seem get the correct answer. Please give some input on what could b

6条回答
  •  抹茶落季
    2020-12-12 00:24

    As already stated errors were two:

    • you used an int that is not big enough to hold that sum.. you should have used a long
    • you used < instead that <=, and it was a wrong guard for the cycle

    Apart from that what you are doing is really inefficient, without going too deep inside this class of algorithms (like Miller-Rabin test) I would suggest you to take a look to the Sieve of Eratosthenes.. a really old approach that teaches how to treat a complex problem in a simple manner to improve elegance and efficiency with a trade-off of memory.

    It's really cleaver: it keeps track of a boolean value for every prime up to your 2 millions that asserts if that number is prime or not. Then starting from the first prime it excludes all the successive numbers that are obtained by multiplying the prime it is analyzing for another number. Of couse more it goes and less numbers it will have to check (since it already excluded them)

    Code is fair simple (just wrote it on the fly, didn't check it):

        boolean[] numbers = new boolean[2000000];
        long sum = 0;
    
        for (int i = 0; i < numbers.length; ++i)
            numbers[i] = true;
    
        for (int i = 2; i < numbers.length; ++i)
            if (!numbers[i])
                continue;
            else {
                int j = i + i;
                while (j < 2000000) {                   
                    numbers[j] = false;
                    j += i;
                }           
            }
    
        for (int i = 2; i < 2000000; ++i)
            sum += numbers[i] ? i : 0;
    
        System.out.println(sum);
    

    Of course this approach is still unsuitable for high numbers (because it has to find all the previous primes anyway and because of memory) but it's a good example for starters to think about problems..

提交回复
热议问题