Euclidean greatest common divisor

Euclidean greatest common divisor

Junior high school mathematics, quickly forget the recap.

If the request 615 and 1997 greatest common divisor of two positive integers, with the Euclidean algorithm, is carried out:
1997/3 = 615 (152 I)
615/152 = 4 (I 7)
152/21 = 7 (I 5)
7/5 = 1 (I 2)
5/2 = 2 (I 1)
2/1 = 2 (I 0)
At this point, a greatest common divisor of 1

Ideas: gcd (a, b) = gcd (b, a% b), where gcd denotes greatest common divisor of a and b;

Code 1:

# python 
m = max(num1, num2)
n = min(num1, num2)
r = m % n
while r != 0:
    m = n
    n = r
    r = m % n
return n
       

Code:

def gcd(m,n):
	return gcd(n,m%n) if n else m #三目运算符,条件运算符
print(gcd(15,25))
# 输出5      

time complexity:

After the amount of data becomes twice the original half the worst operating
time complexityO (lie)

Published 20 original articles · won praise 1 · views 191

Guess you like

Origin blog.csdn.net/weixin_43973433/article/details/105007066