首页 > 解决方案 > 如何添加到累积字符串:

问题描述

在我的一个实验室中,我必须生成所有毕达哥拉斯三元组,直到达到特定的最大值。我发现了如何获取它们,但不知道如何将它们中的每一个添加到特定的字符串中。如何更改代码使输出看起来像这样?

3 4 5
5 12 13
7 24 25
8 15 17
9 40 41
11 60 61
12 35 37
13 84 85

代码:

private int greatestCommonFactor(int a, int b, int c)
{
    int max = number;

    for (a = 1; a <= max; a++) 
    {
        for (b = a; b <= max; b++) 
        {
            for (c = 1; c <= max; c++) 
            {
                if (a * a + b * b == c * c) 
                {
                    
                }
                else
                {
                    continue;
                }
            }
        }
    }
    
    return 1;
}


public String toString(){
    String output = ;
    return output+"\n";
}

标签: java

解决方案


你不应该传递a,b,c给方法,它们只是局部变量,但你可以传递max. 然后你不需要迭代 for ,只需从和c计算它ab

private static void greatestCommonFactor(int max) {
    for (int a = 1; a <= max; a++) {
        for (int b = a; b <= max; b++) {
            double c = Math.sqrt(a * a + b * b);
            if (c == Math.floor(c)) { 
                System.out.println(a + " " + b + " " + (int) c);
            }
        }
    }
}

调用为greatestCommonFactor(50);


您可以将条件更改if (c == Math.floor(c) && c < max)为您喜欢的


推荐阅读