Reputation: 83
I wrote a program to find gcd using python.
def gcd(a,b):
r=a%b
if r==0:
return a
elif r==1:
return 1
else:
gcd(a,b)==gcd(b,r)
return gcd(b,r)
Whenever I call the function it shows the message "Max. recursion exceeded." Please help I know it can be done using looping but I want to specifically do it by using recursion method. And bear with me. I am a learner!
Upvotes: 1
Views: 8704
Reputation: 24567
If you're trying to calculate the GCD of very large numbers (e.g., when searching for common factors in RSA moduli), you might be better off avoiding recursion altogether and using an iterative function instead. For example:
def gcd(a,b):
while a:
a,b = b%a,a
return b
Upvotes: 3
Reputation: 1
This is how I did it
def gcd(m,n):
if m >= n:
r = m % n
if r == 0:
return n
else:
m = n
n = r
return gcd(m,n)
else:
temp = m
m = n
n = temp
return gcd(m,n)
Upvotes: 0
Reputation: 29794
This statement is unnecessary and it's the one making the recursion endless: gcd(a,b)==gcd(b,r)
because it's calling gcd(a,b)
again and again. Just remove it:
def gcd(a,b):
r=a%b
if r==0:
return a
elif r==1:
return 1
return gcd(b,r)
Note: By the way, you got the formula wrong, you should return b
on the if clause since you're dividing a/b
when calculating the modulo.
def gcd(a,b):
r=a%b
if r==0:
return b
elif r==1:
return 1
return gcd(b,r)
>>>gcd(10,4)
2
Upvotes: 3
Reputation: 50868
gcd(a,b)==gcd(b,r)
doesn't do what you expect it to do.
It doesn't mean "define gcd(a,b) to be equal to gcd(b,r)".
Instead, gcd(a,b)==gcd(b,r)
means:
gcd(a,b)
gcd(b,r)
Since you're asking to compute gcd(a, b)
in order to compute gcd(a, b)
, you'll get an endless recursion.
Instead, you want the return gcd(b, r)
at that point. I.e.:
def gcd(a,b):
r=a%b
if r==0:
return a
elif r==1:
return 1
else:
return gcd(b,r)
Upvotes: 1