I am asked to find the greatest common divisor of integers x and y using a recursive function in Python. The condition says that: if y is equal to 0 then gcd (x,y) is x; otherwise gcd(x,y) is 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 xelse: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'
Thank you in advance.
Best Answer
Try this, easy change:
def gcd(x , y):if y == 0:return xelse:return gcd(y, x % y)
compared with math.gcd:
In [1231]: gcd(127,127**2) Out[1231]: 127In [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 xelse: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: 46Enter a value for y: 122
Recursive functions call themselves. You are not calling gcd
from within gcd
so you haven't followed the assignment's directions.
You return 0 as a base condition so that you don't end up with a 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.
Please read this example.
https://www.freecodecamp.org/news/recursion-is-not-hard-858a48830d83/