[英]How to find greatest common divisor using recursive function in Python?
I am asked to find the greatest common divisor of integers x and y using a recursive function in Python.我被要求使用 Python 中的递归函数找到整数x和y 的最大公约数。 The condition says that: if y is equal to 0 then gcd (x,y) is x ;条件表示:如果 y 等于 0,则 gcd (x,y) 是x ; otherwise gcd(x,y) is gcd(y,x%y).否则 gcd(x,y) 是 gcd(y,x%y)。 To try the code, I am asked to obtain two integers from the user.为了尝试代码,我被要求从用户那里获取两个整数。 Here is what I tried:这是我尝试过的:
def gcd(x , y):
if y == 0:
return x
else:
return (y, x % y)
num_one = int(input('Enter a value for x: '))
num_two = int(input('Enter a value for y: '))
if num_two == 0:
print(num_one)
else:
print(gcd(num_two))
And this is the error I get: TypeError: gcd() missing 1 required positional argument: 'y'这是我得到的错误: TypeError: gcd() missing 1 required positional argument: 'y'
Thank you in advance.先感谢您。
Try this, easy change:试试这个,简单的改变:
def gcd(x , y):
if y == 0:
return x
else:
return gcd(y, x % y)
compared with math.gcd:与 math.gcd 相比:
In [1231]: gcd(127,127**2)
Out[1231]: 127
In [1232]: math.gcd(127, 127**2)
Out[1232]: 127
and change this:并改变这一点:
print(gcd(num_two))
to至
print(gcd(num_one, num_two))
Full changes:完整的变化:
def gcd(x , y):
if y == 0:
return x
else:
return gcd(y, x % y)
num_one = int(input('Enter a value for x: '))
num_two = int(input('Enter a value for y: '))
if num_two == 0:
print(num_one)
else:
print(gcd(num_one, num_two))
output:输出:
Enter a value for x: 46
Enter a value for y: 12
2
Recursive functions call themselves.递归函数调用自身。 You are not calling gcd
from within gcd
so you haven't followed the assignment's directions.你是不是叫gcd
从内部gcd
,所以你没有按照指定的方向。
You return 0 as a base condition so that you don't end up with a stackoverflow :)您返回 0 作为基本条件,这样您就不会以stackoverflow结束 :)
Then, you call the method itself from within the containing method.然后,您从包含方法中调用方法本身。 In your case, you are just missing gcd
on line 5 before the opening parenthesis.在您的情况下,您只是在gcd
括号之前缺少第 5 行的gcd
。
Please read this example.请阅读这个例子。
https://www.freecodecamp.org/news/recursion-is-not-hard-858a48830d83/ https://www.freecodecamp.org/news/recursion-is-not-hard-858a48830d83/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.