python 中的互质整数和毕达哥拉斯三元组

coprime integers and Pythagorean Triplets in 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)

输入应该类似于 exp。 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.")