This code snippet defines two functions: one to calculate the Greatest Common Divisor (GCD) using the Euclidean algorithm and another to calculate the Least Common Multiple (LCM) using the GCD.
def gcd(a, b):
if a == 0:
return b
elif b == 0:
return a
elif a > b:
return gcd(a - b, b)
else:
return gcd(a, b - a)
def lcm(a, b):
return a * b / gcd(a, b)
a, b = 20, 8
print("Least common multiple is: " + str(lcm(a, b)))
Least common multiple is: 40.0
gcd(a, b)
def gcd(a, b):
if a == 0:
return b
elif b == 0:
return a
elif a > b:
return gcd(a - b, b)
else:
return gcd(a, b - a)
a
and b
.a
: The first integer.b
: The second integer.if a == 0
: If a
is 0, the GCD is b
. This is because the GCD of 0 and any number b
is b
.elif b == 0
: If b
is 0, the GCD is a
. Similarly, the GCD of 0 and any number a
is a
.elif a > b
: If a
is greater than b
, the function calls itself with a - b
and b
. This step reduces the value of a
by subtracting b
from it.else
: If b
is greater than or equal to a
, the function calls itself with a
and b - a
. This step reduces the value of b
by subtracting a
from it.This process continues recursively until one of the base cases is met, effectively reducing the problem size at each step.
lcm(a, b)
def lcm(a, b):
return a * b / gcd(a, b)
a
and b
.a
: The first integer.b
: The second integer.a
and b
and then divides the product by the GCD of a
and b
, which is calculated using the gcd
function.a, b = 20, 8
a
and b
are initialized with the values 20
and 8
respectively.print("Least common multiple is: " + str(lcm(a, b)))
lcm
function is called with a
and b
as arguments.20
and 8
, is converted to a string and concatenated with the message “Least common multiple is: “.For lcm(20, 8)
, the function will perform the following steps:
gcd(20, 8)
20 > 8
, so it calls gcd(20 - 8, 8)
which is gcd(12, 8)
.12 > 8
, so it calls gcd(12 - 8, 8)
which is gcd(4, 8)
.4 < 8
, so it calls gcd(4, 8 - 4)
which is gcd(4, 4)
.4 == 4
, so it calls gcd(4, 4 - 4)
which is gcd(4, 0)
.b == 0
, it returns 4
.lcm(20, 8)