python中的互素整数和勾股三元组



我是Python的新手。有人给我一个任务,上面有一个这样的例子。我的任务是找到另一种方法来证明a,b,c是共素整数,并用输入c计算毕达哥拉斯三元组。有人能给我展示另一种或类似的方法来解决这个问题吗?

c = int(input('c: ')) 
sol = 'No solution'
ab = True #Definition of ab
bc = True #Definition of bc
ac = True #Definition of ac
for b in range (3, c):
for a in range (2, b):
if (a**2 + b**2) / (c**2) == 1:
for i in range (2, a+1):
if b % i == 0 and a % i == 0: #Coprime integers a,b
ab = False
break
else:
ab = True
for j in range (2, b+1):
if b % j == 0 and c % j == 0: #Coprime integers b,c
bc = False
break
else:
bc = True
for k in range (2, a+1):
if a % k == 0 and c % k == 0: #Coprime integers a,c
ac = False
break
else:
ac = True

if ab==True and bc==True and ac==True: #Coprime integers a,b,c
sol = "%i^2 + %i^2 = %i^2" % (a,b,c) #output
print(sol)

输入应该像表达式c:5,输出应该是3^2+4^2=5^2。提前谢谢。

使用欧几里得gcd函数可以极大地清理代码(两个数字是互质的,当且仅当它们的gcd为1(:

from math import gcd
c = int(input('c: '))
found_sol = False
for b in range(3, c):
for a in range(2, b):
if a**2 + b**2 == c**2:
valid = True
if gcd(a, b) != 1 or gcd(a, c) != 1 or gcd(b, c) != 1:
continue
print(f"{a}^2 + {b}^2 = {c}^2")
found_sol = True
if not found_sol:
print("No solution found.")

另外,您知道a必须等于sqrt(c**2 - b**2),所以您可以保存一个循环:

from math import sqrt, gcd
c = int(input('c: '))
found_sol = False
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
for b in range(3, c):
a = int(sqrt(c**2 - b**2))
if a < b and a**2 + b**2 == c**2:
valid = True
if gcd(a, b) != 1 or gcd(a, c) != 1 or gcd(b, c) != 1:
continue
print(f"{a}^2 + {b}^2 = {c}^2")
found_sol = True
if not found_sol:
print("No solution found.")

最新更新