Calculate Least Common Multiple Using JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to calculate the least common multiple of two or more numbers using JavaScript. We will use the greatest common divisor (GCD) formula and the fact that lcm(x, y) = x * y / gcd(x, y) to determine the least common multiple. The GCD formula uses recursion, which we will implement in our code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28467{{"`Calculate Least Common Multiple Using JavaScript`"}} javascript/data_types -.-> lab-28467{{"`Calculate Least Common Multiple Using JavaScript`"}} javascript/arith_ops -.-> lab-28467{{"`Calculate Least Common Multiple Using JavaScript`"}} javascript/comp_ops -.-> lab-28467{{"`Calculate Least Common Multiple Using JavaScript`"}} javascript/higher_funcs -.-> lab-28467{{"`Calculate Least Common Multiple Using JavaScript`"}} javascript/spread_rest -.-> lab-28467{{"`Calculate Least Common Multiple Using JavaScript`"}} end

Calculating Least Common Multiple

To calculate the least common multiple of two or more numbers, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the greatest common divisor (GCD) formula and the fact that lcm(x, y) = x * y / gcd(x, y) to determine the least common multiple.
  3. The GCD formula uses recursion.
  4. Implement the following code in JavaScript:
const lcm = (...arr) => {
  const gcd = (x, y) => (!y ? x : gcd(y, x % y));
  const _lcm = (x, y) => (x * y) / gcd(x, y);
  return [...arr].reduce((a, b) => _lcm(a, b));
};

Example usage:

lcm(12, 7); // 84
lcm(...[1, 3, 4, 5]); // 60

Summary

Congratulations! You have completed the Least Common Multiple lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like