java - 给定最大长度求毕达哥拉斯三元和

标签 java math

最近我无法确定我遇到的问题的解决方案。我的代码在此过程中跳过了某些毕达哥拉斯三元组,因此给出了不正确的总和。

例如,如果我给最大长度 15(斜边不能大于这个数字)。

它将打印:

3-4-5

5-12-13

然而,存在三个最大边长为 15 的毕达哥拉斯三元组:

3-4-5

8-6-10 - 我错过了这个 :(

5-12-13

我理解手头的问题,但我不确定如何创建有效的解决方案(不创建不必要的循环)。也许有人可以为我指出正确的方向,并在可能的情况下简化我的代码。我总是愿意学习!

class toymeister{

public static void main(String args[]){
    int inputLength = 15;

    System.out.println("Given the length: " + inputLength + 
        " the sum of the pythagorean triplets in the given range is: " 
        + sumTripletsGivenLength(inputLength));
}

public static int sumTripletsGivenLength(int length){
    boolean isFinished = false;
    int m,n = 0;
    int sum=0;

    while(!isFinished){
        n++; {
            m=n+1; {

                int a,b,c;

                a = m*m - n*n;
                b = 2*m*n;
                c = m*m + n*n;

                if(c<length){
                    System.out.println(a + "-" + b + "-" + c);
                    sum = sum+a+b+c;
                } else {
                    isFinished = true;
                }
            }
        }
    }
    return sum;
}
}

最佳答案

这是您的 sumTripletsGivenLength() 方法的有效实现:

public static int sumTripletsGivenLength(int length){
    int sum = 0;

    // the two for loops below are structured such that duplicate pairs
    // of values, e.g. (3, 4) and (4, 3), do not occur
    for (int a=1; a < length; ++a) {
        for (int b=a; b < length; ++b) {
            // calculate hypotenuse 'c' for each combintation of 'a' and 'b'
            double c = Math.sqrt(Math.pow(a, 2.0) + Math.pow(b, 2.0));

            // check if 1) 'c' be a whole number, and 2) its length is within range
            if (c == Math.ceil(c) && c < length) {
                sum = a + b + (int)c;
                System.out.println(a + "-" + b + "-" + (int)c);
            }
        }
    }

    return sum;
}

public static void main(String args[]) {
    int inputLength = 15;

    System.out.println("Given the length: " + inputLength + 
        " the sum of the pythagorean triplets in the given range is: " 
        + sumTripletsGivenLength(inputLength));
}

输出:

3-4-5
5-12-13
6-8-10
Given the length: 15 the sum of the pythagorean triplets in the given range is: 24

关于java - 给定最大长度求毕达哥拉斯三元和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33819049/

相关文章:

javascript - 颜色从蓝色跳到紫色

linq - 为什么空集的总和为空?

python - 我们可以只计算一个非常大的稀疏矩阵的第 n 个特征值和特征向量吗?

java - 计算 BigInteger 中的小数位数

java - 无法让小程序读取文本文件

java - 有没有办法减少我使用的 "if"语句的数量?

java - 创建一个包含隐藏二进制数据的 wav 并读取它(Java)

java - Weblogic 服务器 Guava NoSuchMethodError

java - java如何存储数据结构

java - 排列操作数和运算符以获得数字