Tutorialspoint
Problem
Solution
Submissions

Find the LCM (Least Common Multiple) of Two Numbers

Certification: Basic Level Accuracy: 69.77% Submissions: 43 Points: 5

Write a Python program that calculates the Least Common Multiple (LCM) of two positive integers.

Example 1
  • Input: a = 12, b = 15
  • Output: 60
  • Explanation:
    • Step 1: Find the greatest common divisor (GCD) of 12 and 15, which is 3.
    • Step 2: Calculate LCM using the formula: LCM(a,b) = (a * b) / GCD(a,b)
    • Step 3: LCM = (12 * 15) / 3 = 180 / 3 = 60
    • Step 4: Return 60 as the LCM.
Example 2
  • Input: a = 7, b = 9
  • Output: 63
  • Explanation:
    • Step 1: Find the greatest common divisor (GCD) of 7 and 9, which is 1.
    • Step 2: Calculate LCM using the formula: LCM(a,b) = (a * b) / GCD(a,b)
    • Step 3: LCM = (7 * 9) / 1 = 63 / 1 = 63
    • Step 4: Return 63 as the LCM.
Constraints
  • 1 ≤ a, b ≤ 10^6
  • Time Complexity: O(log(min(a, b))) for the GCD calculation
  • Space Complexity: O(1) as no additional space is needed
StringsGoogleEY
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use formula: LCM(a, b) = (a * b) / GCD(a, b)
  • Find GCD first, then compute LCM
  • Avoid overflow by using: LCM(a, b) = (a // gcd(a, b)) * b

The following is the code to find the least common multiple in two numbers:

  • Define the function lcm(a, b).
  • Use the formula lcm = (a * b) // gcd(a, b) where gcd is calculated using the Euclidean algorithm.
  • Return the calculated LCM.
  • Call the function and print the result.

Submitted Code :