LearnFrenzy
Sign in Take a free test

Loops · Loops Coding Problems · Question 5

GCD and LCM with Euclid's algorithm in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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)}`);
}

Output Verified by running it on Node.js

GCD(12, 18) = 6, LCM = 36
GCD(48, 180) = 12, LCM = 720
GCD(17, 5) = 1, LCM = 85
GCD(21, 6) = 3, LCM = 42

Euclid replaces (a, b) with (b, a % b) until b is 0. LCM × GCD = a × b, so LCM = a / GCD × b.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links