Generating unique, ordered Pythagorean triplets

前端 未结 19 1294
借酒劲吻你
借酒劲吻你 2020-11-29 16:57

This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can

19条回答
  •  日久生厌
    2020-11-29 17:39

    You should define x < y < z.

    for x in range (1, 1000):
        for y in range (x + 1, 1000):
                for z in range(y + 1, 1000):
    

    Another good optimization would be to only use x and y and calculate zsqr = x * x + y * y. If zsqr is a square number (or z = sqrt(zsqr) is a whole number), it is a triplet, else not. That way, you need only two loops instead of three (for your example, that's about 1000 times faster).

提交回复
热议问题