GCD and LCM Calculator - Problem

Write two functions to calculate the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of two positive integers.

The GCD should be implemented using the Euclidean algorithm, which repeatedly applies the formula: gcd(a, b) = gcd(b, a % b) until one number becomes zero.

The LCM should be calculated using the relationship: lcm(a, b) = (a × b) / gcd(a, b)

Return both values as an array [gcd, lcm].

Input & Output

Example 1 — Basic Case
$ Input: a = 48, b = 18
Output: [6, 144]
💡 Note: GCD(48, 18): 48 = 18×2 + 12, 18 = 12×1 + 6, 12 = 6×2 + 0. So GCD = 6. LCM = (48×18)/6 = 864/6 = 144
Example 2 — Co-prime Numbers
$ Input: a = 15, b = 28
Output: [1, 420]
💡 Note: 15 and 28 share no common factors except 1, so GCD = 1. LCM = (15×28)/1 = 420
Example 3 — One Divides Other
$ Input: a = 20, b = 5
Output: [5, 20]
💡 Note: Since 5 divides 20 evenly, GCD = 5 (the smaller number). LCM = 20 (the larger number)

Constraints

  • 1 ≤ a, b ≤ 106
  • Both numbers are positive integers

Visualization

Tap to expand
INPUTALGORITHMRESULT4818Two positive integers148 % 18 = 12218 % 12 = 6312 % 6 = 04GCD = 6 foundEuclidean AlgorithmGCD = 6LCM = 144(48×18)/6Final answer array:[6, 144]Key Insight:The Euclidean algorithm finds GCD in logarithmic time by repeatedly taking remainders until zeroTutorialsPoint - GCD and LCM Calculator | Euclidean Algorithm
Asked in
Microsoft 25 Amazon 20 Google 18
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen