Sunday, 10 August 2025

LCM of two numbers without built-in functions

LCM of Two Numbers

LCM (Least Common Multiple) of two given numbers without using built-in math functions or user-defined functions.

# LCM of two numbers without use of built-in functions.

# Input two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Store the maximum of num1 and num2
if num1 > num2:
    max_num = num1
else:
    max_num = num2

# Find LCM using loop
while True:
    if (max_num % num1 == 0) and (max_num % num2 == 0):
        lcm = max_num
        break
    max_num += 1

# Display the result
print("LCM of", num1, "and", num2, "is", lcm)

Output of program

Enter first number: 5

Enter second number: 7

LCM of 5 and 7 is 35


Saturday, 9 August 2025

Python program to find LCM of Two Numbers

LCM of Two Numbers

Following python program will find the LCM of two given numbers.

import math
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
lcm = abs(a*b) // math.gcd(a, b)
print(f"LCM of {a} and {b} is {lcm}")

Output of program 

Enter first number: 5 Enter second number: 7 LCM of 5 and 7 is 35

Explanation

LCM (Least Common Multiple) is the smallest number that is divisible by both numbers.

In other words:
  • It must be a multiple of 5
  • It must be a multiple of 7
  • And it should be the smallest such number.
List multiples of each number
  • Multiples of 5: 5, 10, 15, 20, 25, 30, 35, 40, …
  • Multiples of 7: 7, 14, 21, 28, 35, 42, …
Find the first common multiple

Looking at both lists:
  • The first number that appears in both lists is 35.
So, LCM(5, 7) = 35.