Compute the greatest common divisor and least common multiple of two integers
Expt. No.14
Page No.28
GCD and LCM
Aim
To write a Python program that finds the GCD (HCF) and the LCM of two integers.
Concepts used
Algorithm
- Input two integers a and b.
- Copy them into x and y.
- While y is not 0, replace x, y with y, x % y (Euclid's method).
- x is now the GCD.
- LCM = a × b ÷ GCD.
- Display both.
Program
# GCD and LCM of two integers (Euclid's method) a = int(input("Enter the first number : "))b = int(input("Enter the second number: "))x = ay = bwhile y != 0: x, y = y, x % ygcd = xlcm = a * b // gcdprint("GCD of", a, "and", b, "is", gcd)print("LCM of", a, "and", b, "is", lcm)
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python gcd_and_lcm.py
Enter the first number : 24
Enter the second number: 36
GCD of 24 and 36 is 12
LCM of 24 and 36 is 72
✓ Printed by running this program, not typed by hand.
Result
For 24 and 36 the GCD was 12 and the LCM was 72, and 12 × 72 = 24 × 36 = 864 as expected.
Viva voce: what the examiner may ask
01How does Euclid's method work?
The GCD of x and y is the same as the GCD of y and x % y. Repeating this until the remainder is 0 leaves the GCD in x.
02How are GCD and LCM related?
GCD × LCM = a × b, so LCM = a × b // GCD.
03Why is // used for the LCM?
It gives an integer result; / would give a float such as 72.0.
Variations for the lab test
- Find the GCD by checking every number from 1 to the smaller number.
- Find the GCD of three numbers.
- Compare your answer with
math.gcd().
! Common mistake Using a and b directly in the loop: they become 12 and 0, so the LCM formula divides 0 and gives 0.