现在我以这种方式计算(原始)毕达哥拉斯三重奏
def generateTriples(limit):
for n in xrange(1, limit):
if (n**2 + (n+1)**2 > limit):
break
for m in xrange(n+1, limit, 2):
if (n**2 + m**2 > limit):
break
if (gcd(n, m) > 1):
continue
yield (m**2 - n**2, 2*m*n, m**2 + n**2)
但这样做的是输出所有三条腿都小于或等于极限的三元组。例如:
for triple in generateTriples(25):
print triple
'''
(3, 4, 5)
(15, 8, 17)
(5, 12, 13)
(7, 24, 25)
'''
但我想做的就是改变它,这样我才能限制腿部。斜边可以是它想要的大 - 我只想让min(leg1,leg2)小于或等于极限。
我也打算生成非原语,这意味着在所有条件上按k缩放(也使得min(leg1,leg2)是< =极限,但我担心我会以这种方式获得重复。
非常感谢任何建议。
答案 0 :(得分:3)
此功能确定可以与完美三联中的腿配对的最大可能的hypoteneuse,然后使用您的函数实际搜索三元组:
from fractions import gcd
def generateTriples(limit):
for n in xrange(1, limit):
if (n**2 + (n+1)**2 > limit):
break
for m in xrange(n+1, limit, 2):
if (n**2 + m**2 > limit):
break
if (gcd(n, m) > 1):
continue
yield (m**2 - n**2, 2*m*n, m**2 + n**2)
def generate_triples_limit_leg(leg):
limit = leg**2 / 2 + 1
for triple in generateTriples(limit):
if min(triple) <= leg:
yield triple
print list(generate_triples_limit_leg(i))
此版本找不到所有三元组,但直接在最小腿上工作:
def generate_triples(limit):
# for each number up to the limit
# Python ranges don't include the max number
# start from 4 because 1 and 2 are invalid
# and 3 and 4 give the same triplet
for i in range(4, limit + 1):
# if i is odd
if i % 2:
# the two larger legs are the integers
# above and below half of the square of the smallest leg
# // is floor division
big = i**2 // 2
yield i, big, big + 1
else:
# the two other legs are the integers
# above and below half of the smallest leg squared
big = (i // 2)**2
yield i, big - 1, big + 1
print list(generate_triples(10))
# [(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25),
# (8, 15, 17), (9, 40, 41), (10, 24, 26)]