我需要关于以下练习题的快速提示:
Write a program that generates all Pythagorean triples whose small sides are no larger than n. Try it with n <= 200.
什么是“不超过 n”??
练习来源:Java by Dissection(Ira Pohl 和 Charlie McDowell)
注意:我发现看起来非常好 post on pythagorean triples但我还不会读它,因为它可能会破坏我自己解决这个问题的尝试....
编辑
如果n是小边a的长度,我们说:n是5; 然后我需要用 a=1,a=2,a=3,a=4,a=5 检查所有三元组 并找到毕达哥拉斯三元组的情况
这个额外条件有什么用?
编辑 2
如果我向您展示一个实用的片段,也许我会更接近……所以这里是一小段(python)代码,它返回几个三元组。我已将外循环的上限设置为 20(目前我看不到 'n' 的任何其他用途)以使其易于管理。
import math
for b in range(20):
for a in range(1, b):
c = math.sqrt( a * a + b * b)
if c % 1 == 0:
print (a, b, int(c))
返回
(3, 4, 5) (6, 8, 10) (5, 12, 13) (9, 12, 15) (8, 15, 17) (12, 16, 20)
这是期望的输出吗?我缺少的步骤是什么?
提前致谢
爸爸
最佳答案
毕达哥拉斯三元组是直角三角形的整数边。三角形的小边是形成直角的边(不是斜边)。
no larger than n
意味着给你一个整数 n
并且必须生成所有可能的整数三元组 a b c
这样 a <= n, b <= n
和 a^2 + b^2 = c^2
.
关于algorithm - 毕达哥拉斯三元组练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3976466/