java - Project Euler 9 解决方案没有给出正确的结果

标签 java algorithm combinatorics

问题是:

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

所以使用函数 tripletP() 我认为该程序会为数字 1000 生成 3 个求和器的所有可能组合。 这段代码中的函数 isTriplet(a,b,c) 永远不会返回 true,最后 int product 的值为 0。 我似乎找不到我逻辑中的缺陷,我们将不胜感激。

这是我的 Java 类,其中包含我认为可以解决问题 9 的代码:

public class ProblemNine {


    public static void main(String[] args) {

        ProblemNine f = new ProblemNine();
        System.out.println(f.tripletP());

    }

    boolean isTriplet(int a, int b, int c){

        if((a*a)+(b*b)==(c*c)){
            return true;
        } else return false;    
    }

    int tripletP(){
        int a=1,b=2,c=997;
        int product = 0;

        //outerloop generates all possible combinations of 3 summators for the number 1000, if b>c>a is true
        outerloop:
        for(int i = 997; i>499; i--){
            c = i;
            b = 999-i;
            a = 1;

            while(b>(a+2) && (a+b) == (1000-i) && a!=b && c>b){
                b--;
                a++;
                // supposedly checks if a,b,c are a triplet.
                if (isTriplet(a,b,c)){
                    product=a*b*c;
                    break outerloop;
                }
            }   

            if(c>997 || b>499 || a>249){
                break outerloop;
            }
        }

        return product;
    }

}

最佳答案

for(int i = 997; i>499; i--){

你停得太早了。如果a<b<ca+b+c == 1000 ,c 的最小可能值不是 500,而是 335。

for(int i = 997; i>335; i--){

有了这个新的下界,b偶尔会大于 c ,这会过早地触发你的一些条件。不过,您可以删除它们并仍然得到正确答案。

    for(int i = 997; i>335; i--){
        c = i;
        b = 999-i;
        a = 1;

        while(b>(a+2)){
            b--;
            a++;
            if (isTriplet(a,b,c)){
                product=a*b*c;
                break outerloop;
            }
        }
    }

关于java - Project Euler 9 解决方案没有给出正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330847/

相关文章:

java - 仅包含 Firebase 插件的简单 Cordova 应用程序无法在 Android 上构建或运行

java - 如何动态更改 ImageView (JavaFX) 中的图像?

用于折叠时间轴上重叠事件的算法/数据结构

java - 随机数生成算法

二进制组合计数

kotlin - 如何以函数式风格生成一定长度的非穷举排列

java - 将一个组分成大小为 k 的子组

java - 使用 restclient 或 postman 发送 gzip 数据

java - 如何从用户输入错误的地方重复输入?

algorithm - 平面度测试算法实现