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

标签 java algorithm debugging

<分区>

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

问题描述:

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(;;){ 之间。

关于java - Java 中的 Project Euler #50(解决方案无效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913825/

相关文章:

java - Android 应用程序上未显示图像

algorithm - 如何识别交通标志的形状?

debugging - Xamarin 跳过了一个可等待的方法

Javascript:根据下拉列表选择显示/隐藏div

java - 从另一个 portlet (Liferay + Spring) 获取 Portlet Application Context

java - 保存复选框的选择

java - 我如何使用 Java 中的 Selenium 选择这个元素?

c# - 在没有两个或多个连续 6 的情况下查找下一个数字的算法

java - 错误 : java. util.NoSuchElementException - 扫描仪未按预期运行

debugging - 减少托管程序的小型转储的大小,同时保留一些堆信息?