首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >求给定最大长度的Pythogorean三重和

求给定最大长度的Pythogorean三重和
EN

Stack Overflow用户
提问于 2015-11-20 04:34:01
回答 1查看 44关注 0票数 3

最近,我一直无法找到解决问题的办法。我的代码在这个过程中跳过了某些Pythagorean三胞胎,因此给出了不正确的和。

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

它将印刷:

3-4-5

5-12-13

然而,有三个毕达哥拉斯三重奏,给定的最大边长为15:

3-4-5

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

5-12-13

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

代码语言:javascript
复制
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;
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-20 05:15:04

下面是sumTripletsGivenLength()方法的一个工作实现:

代码语言:javascript
复制
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));
}

输出:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33819049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档