Tutorialspoint
Problem
Solution
Submissions

Find GCD and LCM

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to find the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of two positive integers. The GCD is the largest positive integer that divides both numbers without a remainder. The LCM is the smallest positive integer that is divisible by both numbers. Use the relationship: LCM(a, b) = (a * b) / GCD(a, b).

Example 1
  • Input: a = 12, b = 18
  • Output: GCD = 6, LCM = 36
  • Explanation:
    • Find factors of 12: 1, 2, 3, 4, 6, 12.
    • Find factors of 18: 1, 2, 3, 6, 9, 18.
    • Common factors are: 1, 2, 3, 6.
    • The greatest common factor is 6, so GCD = 6.
    • Calculate LCM using the formula: LCM = (12 * 18) / 6 = 216 / 6 = 36.
Example 2
  • Input: a = 8, b = 12
  • Output: GCD = 4, LCM = 24
  • Explanation:
    • Find factors of 8: 1, 2, 4, 8.
    • Find factors of 12: 1, 2, 3, 4, 6, 12.
    • Common factors are: 1, 2, 4.
    • The greatest common factor is 4, so GCD = 4.
    • Calculate LCM using the formula: LCM = (8 * 12) / 4 = 96 / 4 = 24.
Constraints
  • 1 ≤ a, b ≤ 10^9
  • Both numbers are positive integers
  • Time Complexity: O(log(min(a, b)))
  • Space Complexity: O(1)
NumberPwCAdobe
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 Euclidean algorithm to find GCD efficiently
  • The Euclidean algorithm is based on the principle that GCD(a, b) = GCD(b, a % b)
  • Continue the process until one of the numbers becomes 0
  • The other number at that point is the GCD
  • Calculate LCM using the relationship: LCM = (a * b) / GCD

Steps to solve by this approach:

 Step 1: Store the original values of a and b for LCM calculation.
 Step 2: Apply the Euclidean algorithm: while b is not zero, replace a with b and b with a % b.
 Step 3: Continue the process until b becomes 0.
 Step 4: The value of a at this point is the GCD of the original numbers.
 Step 5: Calculate LCM using the formula: LCM = (original_a * original_b) / GCD.
 Step 6: Return both GCD and LCM as an object.
 Step 7: Display the results for the given test cases.

Submitted Code :