简体   繁体   中英

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. 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 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'

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:

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM