Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的互质整数和勾股三元组_Python_Integer_Pythagorean - Fatal编程技术网

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

python中的互质整数和勾股三元组,python,integer,pythagorean,Python,Integer,Pythagorean,我是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):

我是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时):

从数学导入gcd
c=int(输入('c:'))
已找到\u sol=False
对于范围(3,c)内的b:
对于范围(2,b)内的a:
如果a**2+b**2==c**2:
有效=真
如果gcd(a,b)!=1或gcd(a,c)!=1或gcd(b,c)!=1:
持续
打印(f“{a}^2+{b}^2={c}^2”)
已找到\u sol=True
如果未找到\u sol:
打印(“未找到解决方案”)
另外,您知道
a
必须等于
sqrt(c**2-b**2)
,这样您就可以保存一个循环:

来自数学导入sqrt,gcd
c=int(输入('c:'))
已找到\u sol=False
def gcd(a、b):
而b!=0:
a、 b=b,a%b
归还
对于范围(3,c)内的b:
a=int(sqrt(c**2-b**2))
如果a
math.gcd()
存在于python 3.5上。它适用于任意数量的参数。