user1424624
user1424624

Reputation: 1

Thinkof Python Chaper6,exercise8

>>> def gcd(m,n):
        if m%n==r and n !=0 and r !=0:
            return gcd(m,n)==gcd(n,r)
        elif n==0 or r==0:
            return gcd(m,0)==1
        else:
            print None

gcd(5,6)

Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
gcd(5,6)
File "<pyshell#34>", line 5, in gcd
return gcd(m,0)==1
File "<pyshell#34>", line 2, in gcd
if m%n==r and n !=0 and r !=0:
ZeroDivisionError: integer division or modulo by zero

Sorry I just modified it to another version, but still got similar error message... Many thanx to you all!

Upvotes: 0

Views: 88

Answers (2)

Andy
Andy

Reputation: 50560

I suspect you changed your code pasted from gcd(5,0) to gcd(5,6) when posting this question.

Your call to gcd is passing the values 5 and 0, as indicated by your error message. The line if m%n==r: is attempting to perform division by 0 - a mathematical impossibility. That is the reason for your ZeroDivisionError exception

Edit:

Formatting is off so I missed this on first pass, but in the line r=int() you are setting r to 0. That means this line return gcd(m,n)==gcd(n,r) is passing 0 to gcd.

Upvotes: 3

starbolin
starbolin

Reputation: 840

The scalar r is not assigned when gcd() calls itself. This result is a zero for the second parameter. Thus the subsequent division fails.

The second line should probably be 'if m%n=r'

Upvotes: 0

Related Questions