GCD
According to Euclidean Algorithm,
GCD(Greatest Common Divors) of a, b
is same with GCD of b, a % b
Recursive Approach as follows.
In [18]:
1
2
3
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
gcd(60, 48)
1
12
Iterative Approach as follows.
In [19]:
1
2
3
4
5
def gcd(a, b):
while b:
a, b = b, a%b
return a
gcd(60, 48)
1
12
LCD
LCD is easy if you understand GCD.
Simply divide a, b
by gcd(a, b)
.
In [24]:
1
2
3
4
def lcd(a, b):
return int(a * b / gcd(a, b))
lcd(60, 48)
1
240
Reference
[1] Korean Blog
[2] Euclidean Algorithm
Leave a comment