Python Lab · Experiment 12
GCD of two numbers using a function
PythonWeek 3JNTUH R22 · CS206ES
Aim
To write a Python function gcd(a, b) that returns the greatest common divisor of two integers using Euclid's algorithm, and a program that reads two numbers and prints their GCD.
Algorithm
- Define the function gcd(a, b).
- Take the absolute values of a and b, so negative numbers also work.
- While b is not 0, replace (a, b) with (b, a % b).
- When b becomes 0, a is the GCD. Return a.
- In the main program, read two integers, call gcd and print the result.
Program
def gcd(a, b):
"""Return the greatest common divisor of a and b."""
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print(f"GCD of {x} and {y} is {gcd(x, y)}")Output
Numbers with a common factor
Enter the first number: 48
Enter the second number: 18
GCD of 48 and 18 is 6Co-prime numbers
Enter the first number: 17
Enter the second number: 5
GCD of 17 and 5 is 1One number is 0
Enter the first number: 0
Enter the second number: 12
GCD of 0 and 12 is 12Recorded by running this exact program. Typed input appears after each prompt.
How it works
Euclid's algorithm uses the fact that gcd(a, b) = gcd(b, a % b). For 48 and 18: gcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) = 6.
If a is smaller than b, the first pass just swaps them: gcd(18, 48) → gcd(48, 18).
The same function can be written recursively:
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)Python's math module has a ready-made math.gcd, which you can use to check your answers.
Common mistakes
Printing the GCD inside the function instead of returning it. The task asks for a function that returns the value, so the caller can use it.
Writing
a = bandb = a % bon two lines. The second line uses the newa, which is wrong. Usea, b = b, a % b.Using
while a % b != 0without handlingb = 0, which raisesZeroDivisionError. Testingb != 0first avoids this.Finding the GCD by trying every number from 1 to the smaller one. It works but is slow for large numbers; Euclid's method needs very few steps.
Viva questions
Try to answer each one aloud before you open it.
What is the GCD of two numbers?
The greatest common divisor is the largest positive integer that divides both numbers without a remainder. The GCD of 48 and 18 is 6.
Explain Euclid's algorithm.
Repeatedly replace the pair (a, b) by (b, a mod b). When the second number becomes 0, the first number is the GCD.
What is the difference between return and print in a function?
returnsends a value back to the caller, which can store or use it.printonly displays it on the screen; the function then returnsNone.What is the GCD of two co-prime numbers?
- Co-prime numbers have no common factor other than 1.
How are GCD and LCM related?
For positive integers, gcd(a, b) × lcm(a, b) = a × b, so lcm(a, b) = a × b / gcd(a, b).