Tutorialspoint
Problem
Solution
Submissions

LCM of Two Numbers

Certification: Basic Level Accuracy: 60% Submissions: 5 Points: 10

Write a C++ program to find the least common multiple (LCM) of two positive integers.

Example 1
  • Input: a = 12, b = 18
  • Output: 36
  • Explanation:
    • Step 1: Find the GCD of 12 and 18 using Euclidean algorithm.
    • Step 2: GCD(12, 18) = GCD(18, 12%18) = GCD(18, 12) = GCD(12, 18%12) = GCD(12, 6) = GCD(6, 12%6) = GCD(6, 0) = 6.
    • Step 3: Calculate LCM using the formula: LCM(a,b) = (a × b) / GCD(a,b).
    • Step 4: LCM(12, 18) = (12 × 18) / 6 = 216 / 6 = 36.
Example 2
  • Input: a = 5, b = 7
  • Output: 35
  • Explanation:
    • Step 1: Find the GCD of 5 and 7 using Euclidean algorithm.
    • Step 2: GCD(5, 7) = GCD(7, 5%7) = GCD(7, 5) = GCD(5, 7%5) = GCD(5, 2) = GCD(2, 5%2) = GCD(2, 1) = GCD(1, 2%1) = GCD(1, 0) = 1.
    • Step 3: Calculate LCM using the formula: LCM(a,b) = (a × b) / GCD(a,b).
    • Step 4: LCM(5, 7) = (5 × 7) / 1 = 35 / 1 = 35.
Constraints
  • 1 ≤ a, b ≤ 10^6
  • Time Complexity: O(log(min(a, b))) for the Euclidean GCD algorithm
  • Space Complexity: O(1)
NumberVariables and Data TypesTCS (Tata Consultancy Services)Dropbox
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 the formula LCM(a, b) = (a * b) / GCD(a, b).
  • Implement the Euclidean algorithm to compute the GCD.

Steps to solve by this approach:

 Step 1: Create a GCD function using the Euclidean algorithm with a loop.

 Step 2: Inside the GCD function, use temporary variables to swap values.
 Step 3: Continue the algorithm until the second number becomes zero.
 Step 4: Create an LCM function that handles edge cases (if either number is 0).
 Step 5: Calculate LCM using the formula: LCM(a,b) = (a×b)/GCD(a,b).
 Step 6: Return the calculated LCM value.

Submitted Code :