Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

java - How to add to a cumulative String:

In one of my labs, I had to produce all the Pythagorean triples until a specific max. I found out how to get them but not how to add each of them to a specific string. How do I change the code so the output look like this?

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

Code:

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+"
";
}
question from:https://stackoverflow.com/questions/65907351/how-to-add-to-a-cumulative-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should not pass a,b,c to the method, they are just local variables, but you may pass the max. Then you don't need to iterate for c, just compute it from a and b

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);
            }
        }
    }
}

Call as greatestCommonFactor(50);


You can change the condition to if (c == Math.floor(c) && c < max) is you prefer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...