Python 如何找到一对数字的最高公因数?
这是我的密码:Python 如何找到一对数字的最高公因数?,python,Python,这是我的密码: num1= int(input('Enter the first number: ')) num2= int(input('Enter the second number: ')) def hcf(num1,num2): if num2==0: return num1 else: return hcf(num2, num1%num2) print('The highest common factor', (hcf)) h
num1= int(input('Enter the first number: '))
num2= int(input('Enter the second number: '))
def hcf(num1,num2):
if num2==0:
return num1
else:
return hcf(num2, num1%num2)
print('The highest common factor', (hcf))
hcf(num1, num2)
它不像我想象的那样印刷。我需要找到最高公因数。如果你是指“最高公因数”所指的“最大公因数”,你可以使用math.gcd
:
from math import gcd
a = int(input("Number 1: "))
b = int(input("Number 2: "))
print("Greatest common divisor:", gcd(a, b))
在这两个分支中,您使用的
if
和else
返回,因此在此之后不会执行任何代码,因此打印是无法访问的。您可以存储方法的结果(由返回的给出),然后打印它
def hcf(num1,num2):
if num2==0:
return num1
else:
return hcf(num2, num1%num2)
res = hcf(num1, num2)
print('The highest common factor is', res)
您知道,您的最高公因式通常被称为最大公因式所谓的,并且在python的包math
中出现
from math import gcd
res = gcd(num1, num2)
print('The greatest common divisor is', res)
这和他有什么不同?他可以使用很多东西,但这并不能帮助他解决自己的问题。。。