Java 中的 Project Euler #50(解决方案无效)

Project Euler #50 in Java(Solution not working)

我的结果是错误的,但我找不到错误。

问题描述:

The prime 41, can be written as the sum of six consecutive primes:41 = 2 + 3 + 5 + 7 + 11 + 13. This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes?

我的想法:

  1. Starting from the first prime 2, compute the longest sum of consecutive primes that adds to a number below 1 million.
  2. Count down from the longest, for each certain length, compute the sum of seri start from 2, then compute the sum of seri start from the second prime...
  3. Stop when a sum is a prime.

我的代码:

public class Prob50 {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    long sum=0;
    int count=0;
    for(int i = 2; ; i++){
        if(isPrime(i)){
            if((sum+=i)>1000000){
                sum-=i;
                break;
            }
            count++;
        }
    }

    int jump=0;
    boolean isOver= false;
    boolean isAns= false;
    for(;count>0;count--){
        jump=0;

        for(;;){
            int tempj=jump;
            int tempc=count;
            sum=0;
            for(int i = 2;tempc>0 ; i++){

                if(isPrime(i)&&tempj>0){
                    tempj--;
                    continue;
                }

                if(isPrime(i)){
                    tempc--;
                    if((sum+=i)>1000000){
                        sum-=i;
                        isOver=true;
                    }
                }
            }

            if(isPrime(sum)){
                isAns=true;
                break;
            }
            if(isOver){
                break;
            }
            jump++;
        }

        if(isAns){
            break;
        }

    }
    System.out.println(sum+" "+count);
}

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

我的结果:

958577 536

答案是 997651,计数应该是 543。

我想出来了,只需要补充一下:

isOver= false;

介于 isOver= false;for(;;){ 之间。