Greatest Common Divisor and LCM
Write the code, see it run, pass the checks.
The problem
- easy
- Code
Write gcdLcm(a, b) for two whole numbers from 1 to 1,000,000,000: return [gcd, lcm], their greatest common divisor and least common multiple. Their lcm is always below 2 to the power 53, but a × b may not be, and past that JavaScript numbers lose exactness, so don't multiply a by b first. For example, gcdLcm(12, 18) is [6, 36]. The checks include 100,000 pairs, so counting down to the gcd or subtracting the smaller number again and again is too slow: use the remainder instead.
Your code must pass
- Finds the gcd and lcm
- Handles one number dividing the other
- Gets the lcm exactly when a × b is huge
- Is fast enough for 100,000 pairs up to a billion