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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code