Python Question

>Write a function called gcd that takes parameters a and b and returns their greatest common divisordivisor

Answer:

You can implement the greatest common divisor (GCD) function using the Euclidean algorithm. Here’s how you can do it in Python:

“`python

def gcd(a, b):

while b:

a, b = b, a % b

return a

# Example usage:

num1 = 48

num2 = 18

print(“GCD of”, num1, “and”, num2, “is:”, gcd(num1, num2))

“`

In this implementation, the `gcd` function repeatedly applies the Euclidean algorithm until `b` becomes 0. The algorithm states that the GCD of two numbers `a` and `b` is the same as the GCD of `b` and the remainder of `a` divided by `b`. So, in each iteration, `a` becomes `b`, and `b` becomes `a % b`. When `b` becomes 0, `a` will be the GCD of the original `a` and `b`.