Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Find the Least Common Multiple (LCM) of two numbers - Python Program

Example 1 :

# LCM of two numbers a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) greater = max(a, b) while True: if greater % a == 0 and greater % b == 0: lcm = greater break greater += 1 print(f"LCM of {a} and {b} = {lcm}")

Output

 
OUTPUT  :
Enter first number: 4
Enter second number: 6
LCM of 4 and 6 = 12 
 

Explanation

  • Starts from the maximum of both numbers.
  • Increments until it finds a number divisible by both.
  • Alternative: lcm = (a * b) // gcd(a, b) using gcd.

Example 2 : Advanced Program

def gcd(a, b): """ Calculates the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm. """ while b: a, b = b, a % b return a def lcm(a, b): """ Calculates the Least Common Multiple (LCM) of two numbers. """ if a == 0 or b == 0: return 0 # LCM of any number with 0 is 0 return abs(a * b) // gcd(a, b) # Example Usage num1 = 12 num2 = 18 result_lcm = lcm(num1, num2) print(f"The LCM of {num1} and {num2} is: {result_lcm}") num3 = 7 num4 = 5 result_lcm_2 = lcm(num3, num4) print(f"The LCM of {num3} and {num4} is: {result_lcm_2}")

Output

 
OUTPUT  :
The LCM of 12 and 18 is: 36
The LCM of 7 and 5 is: 35