user17285516
user17285516

Reputation:

ZeroDivisionError: integer division or modulo by zero in python

I was writing a program; for finding Greatest common divisor but I receive this an error

h = 0
def GCD(num1, num2):
    if num1 == num2:
        return num1, num2
    elif num1 < num2:
        h = num1
        num1 = num2
        num2 = h
        while num1 % num2 != 0:
            num1 = num2
            num2 = num1 % num2
        return num2
print (GCD(12, 18))

and here is the error I received that ZeroDivisionError: integer division or modulo by zero in this line while num1 % num2 != 0:

full error:

Traceback (most recent call last):
  File "c:\Users\Lenovo\projects\*****.py", line 13, in <module>
    print (GCD(12,18))
  File "c:\Users\Lenovo\projects\*****.py", line 9, in GCD
    while num1 % num2 != 0:
ZeroDivisionError: integer division or modulo by zero

I'm grateful for any helps

Upvotes: 0

Views: 1115

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308138

As pointed out in the comments by j1-lee you are guaranteeing that num2 will become zero with this sequence of operations:

            num1 = num2
            num2 = num1 % num2

You probably wanted to use the original value of num1 in that second line. Fortunately Python makes that easy using tuple packing and unpacking:

            num1, num2 = num2, num1 % num2

The calculations on the right side will be performed before any assignments are made.

Upvotes: 1

Related Questions