What Causes ZeroDivisionError in Euclidean Intersection?

Asked 2 years ago, Updated 2 years ago, 78 views

ZeroDivisionError: integer division or module by zero

Here's the code.

def Euclidean_algo(m,n):

    while m%n!=0:
        m=n
        n = m%n
    else:
        return n


m=int(input('the bigger int is:')
n = int(input('the smaller int is:')
print(Euclidean_algo(m,n))

python algorithm

2022-09-30 21:32

1 Answers

For a moment, it seemed like I was implementing Euclidean reciprocity correctly, but I finally realized when I tried it.

These two lines

m=n
    n = m%n

Because m is first substituted with the current n value, m and n values are the same when n=m%n runs on the second line.Therefore, m%n always results in 0, so n is 0 in the next conditional decision m%n!=0, so a zero division exception occurs.

If you simply change the order of the two lines, you will lose the older n value that should be placed in m, and you can substitute Python at the same time.

def Euclidean_algo(m,n):
    while m%n!=0:
        m,n = n, m%n
    return n

Try this definition.By the way, Euclidean reciprocity works regardless of the size of the two numbers, so you don't need to specify the number of m that is larger.


2022-09-30 21:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.