Given the integers $ a, b (a> b) $, if $ a $ is divided by $ b $ and the remainder is $ r $. Using the fact that the greatest common divisor of $ a $ and $ b $ is equal to the greatest common divisor of $ b $ and $ r $ (the principle of division), the greatest common divisor of $ a and b $ is calculated by repeating the division. How to find it.
Input integers $ a, b $ Output: Greatest common divisor $ d $
euclid.py
def euclid(a,b):
    a_list = []
    if a < b: 
        a_list.append(b)
        a_list.append(a)
    if a >= b:
        a_list.append(a)
        a_list.append(b)
    i = 0
    while(a_list[-1]!=0):
        a_list.append(a_list[i]%a_list[i+1])
        i +=1
    return a_list[-2]
A method of finding one solution of a linear indefinite equation using the following mechanism. When finding $ ax + by = d $, set $ a_0 = a, a_1 = b $.
Input integers $ a, b $ Output: Integers $ x, y $ with the greatest common divisor $ d $ and $ ax + by = d $
exEuclid.py
def exEuclid(a,b):
    a_list = []
    if a < b: 
        a_list.append(b)
        a_list.append(a)
    if a >= b:
        a_list.append(a)
        a_list.append(b)
    q = []
    x = []
    x.append(1)
    x.append(0)
    y = []
    y.append(0)
    y.append(1)
    i = 0
    while(a_list[-1]!=0):
        a_list.append(a_list[i]%a_list[i+1])
        q.append(a_list[i]//a_list[i+1])
        x.append(x[-2]-q[-1]*x[-1])
        y.append(y[-2]-q[-1]*y[-1])
        i +=1
    return x[-2],y[-2],a_list[-2]
        Recommended Posts