j25“`python
def gcd_Euclidean(a, b):
if b == 0:
return a

Image: www.youtube.com
return gcd_Euclidean(b, a % b)
“This code snippet calculates the greatest common divisor (GCD) between two integers
aand
b` using the Euclidean algorithm. Here is a simplified version of the code with comments:
def gcd_Euclidean(a, b):
# If `b` is 0, `a` is the GCD
if b == 0:
return a
# Recursively calculate the GCD of `b` and `a` % `b`
return gcd_Euclidean(b, a % b)
- If
b
is 0, it means thata
is the GCD because there is no more common divisor to find. - If
b
is not 0, the algorithm calculates the remainder (a % b
) whena
is divided byb
. The remainder represents the common divisor betweena
andb
. - The algorithm then makes a recursive call to
gcd_Euclidean
withb
anda % b
. This continues untilb
becomes 0, at which point the algorithm returns the GCD.

Image: www.youtube.com
Ady Trading Options On Nflx
Example
Let’s calculate the GCD of 12 and 18 using the Euclidean algorithm:
- gcd(12, 18) is called.
- Since 18 is not 0, we calculate 12 % 18, which equals 6.
- gcd(18, 6) is called.
- Since 6 is not 0, we calculate 18 % 6, which equals 0.
- We have reached a case where
b
(0) is 0, so gcd(18, 6) returns 6. - This 6 is passed back to the previous recursive call, gcd(18, 6), which also returns 6.
- Finally, gcd(12, 18) returns 6, which is the GCD of 12 and 18.