Introduction:
The greatest common divisor (GCD) and least common multiple (LCM) are two important mathematical concepts.
The GCD of two integers is the largest integer that divides both numbers without leaving a remainder.
The LCM, on the other hand, is the smallest positive integer that is divisible by both numbers.
Objective:
In this tutorial, we will create a Python program to calculate both the GCD and LCM of two integers.
We will use built-in Python functions and implement a method to find the GCD using Euclid’s algorithm,
which is efficient and commonly used. The LCM can be calculated from the GCD using the formula:
LCM(a, b) = |a * b| / GCD(a, b)
Python Code:
# Python Program to Find GCD and LCM
# Function to compute the GCD using Euclid's algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Function to compute the LCM using the formula LCM(a, b) = |a * b| / GCD(a, b)
def lcm(a, b):
return abs(a * b) // gcd(a, b)
# Input: Get two integers from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Calculate GCD and LCM
gcd_result = gcd(num1, num2)
lcm_result = lcm(num1, num2)
# Output the results
print(f"The GCD of {num1} and {num2} is: {gcd_result}")
print(f"The LCM of {num1} and {num2} is: {lcm_result}")
Explanation of the Program Structure:
1. The program defines two functions, gcd(a, b)
and lcm(a, b)
.
2. The gcd(a, b)
function uses Euclid’s algorithm to find the greatest common divisor of the two input numbers.
It works by repeatedly replacing the larger number with the remainder of the two numbers until the remainder becomes zero.
The last non-zero remainder is the GCD.
3. The lcm(a, b)
function calculates the least common multiple using the formula:
LCM(a, b) = |a * b| / GCD(a, b)
.
4. The program prompts the user to enter two integers, which are then passed to the functions to calculate and display the GCD and LCM.
How to Run the Program:
1. Open a Python editor or IDE (such as PyCharm, VSCode, or simply IDLE).
2. Copy and paste the code into a new Python file (e.g., gcd_lcm.py
).
3. Run the program. It will prompt you to input two numbers.
4. After entering the numbers, the program will display the GCD and LCM of the two numbers.