JavaScript Program to Find Smallest Number that is Divisible by First n Numbers

To find the smallest number that is divisible by the first n numbers in JavaScript we need to understand the concept of the Least Common Multiple (LCM). The LCM of a set of numbers is the smallest number that is evenly divisible by each number in the set. Here’s a step-by-step guide to solving this problem programmatically in JavaScript.

Introduction

Finding the smallest number divisible by the first n natural numbers is a classic problem in number theory and programming. It involves calculating the Least Common Multiple (LCM) of a sequence of numbers.

Approach

To solve this problem we can use the following steps:

1. Understanding LCM: Calculate the LCM of numbers from 1 to n. The LCM of two numbers a and b can be found using the formula:


where GCD is the Greatest Common Divisor.

2. Iterative Calculation: Start with the LCM of the first two numbers then iteratively calculate the LCM with the next number until nn.

3. JavaScript Implementation: Write a JavaScript function to compute the LCM iteratively using a loop.

Implementation

Here's the JavaScript code to find the smallest number divisible by the first n numbers:

function findSmallestDivisibleByFirstN(n) {

    function gcd(a, b) {

        // Euclidean algorithm to find GCD

        return b === 0 ? a : gcd(b, a % b);

    }

    function lcm(a, b) {

        // Calculate LCM using the relationship with GCD

        return (a * b) / gcd(a, b);

    }

    // Initialize lcm variable to 1

    let result = 1;

    // Iterate from 2 to n and calculate LCM

    for (let i = 2; i <= n; i++) {

        result = lcm(result, i);

    }

    return result;

}

// Example usage:

let n = 10;

console.log(`The smallest number divisible by the first ${n} numbers is: ${findSmallestDivisibleByFirstN(n)}`);

Output :

The smallest number divisible by the first 10 numbers is: 2520

Explanation

  • gcd Function: The gcd function uses the Euclidean algorithm to calculate the Greatest Common Divisor (GCD) of two numbers.
  • lcm Function: The lcm function computes the LCM of two numbers using the relationship       
  • Main Function: findSmallestDivisibleByFirstN iteratively computes the LCM of numbers from 1 to n using the lcm function.

Post a Comment

Previous Post Next Post