Find the GCD (HCF) and LCM of pairs of numbers using Euclid's algorithm in a while loop.
Solution
main.js
function gcd(a, b) {
while (b !== 0) {
[a, b] = [b, a % b]; // gcd(a, b) = gcd(b, a mod b)
}
return a;
}
const lcm = (a, b) => (a / gcd(a, b)) * b; // divide first to keep numbers small
for (const [a, b] of [[12, 18], [48, 180], [17, 5], [21, 6]]) {
console.log(`GCD(${a}, ${b}) = ${gcd(a, b)}, LCM = ${lcm(a, b)}`);
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!