JavaScript Program to Find Smallest Number that is Divisible by First n Numbers
Last Updated :
24 Jun, 2024
Given a number, our task is to find the smallest number that is evenly divisible by the first n numbers without giving any remainder in JavaScript.
Example:
Input: 10
Output: 2520
Explanation:
2520 is smallest number which is completely divisible by numbers from 1 to 10.
Below are the following approaches for finding the Smallest number that is divisible by the first n numbers:
Brute Force Approach
To Find the smallest number divisible by the first n numbers using Brute Force Approach first initialize num with n. Use a while loop to find the smallest divisible number. In the loop, set divisible to true, and iterate from 1 to n, checking if num is divisible by i. If not, set divisible to false and break. If divisible remains true, return num. Otherwise, increment num and continue.
Example: Demonstration of Finding the Smallest number divisible by the first n numbers using the Brute Force Approach.
JavaScript
function smallDivi(n) {
let num = n;
while (true) {
let divisible = true;
for (let i = 1; i <= n; i++) {
if (num % i !== 0) {
divisible = false;
break;
}
}
if (divisible) {
return num;
}
num++;
}
}
console.log(smallDivi(10));
Time Complexity: O(num * n)
Space Complexity: O(1)
Using LCM (Lowest Common Multiple)
In this approach, first implement gcd to find the greatest common divisor using Euclid's algorithm. Implement lcm to calculate the least common multiple as a * b / gcd(a, b). Initialize the answer to 1 and iterate from 2 to n, updating the answer with the least common multiple of the answer and i. After the loop, the answer holds the smallest number divisible by the first n numbers. Return answer.
Example: Demonstration of Finding the the Smallest number that is divisible by first n numbers using LCM (Lowest Common Multiple).
JavaScript
function smallestDivisibleLCM(n) {
function calculateGCD(a, b) {
return b === 0 ? a : calculateGCD(b, a % b);
}
function calculateLCM(a, b) {
return (a * b) / calculateGCD(a, b);
}
// Initialize the result to 1
let answer = 1;
// Iterate through numbers from 2 to n to calculate LCM
for (let i = 2; i <= n; i++) {
answer = calculateLCM(answer, i);
}
return answer;
}
console.log(smallestDivisibleLCM(10));
Time Complexity: O(n * log(n)).
Space Complexity: O(1).
Using Prime Factorization Method:
The Prime Factorization Method calculates the smallest number divisible by the first n numbers by identifying all primes up to n, determining the highest power of each prime that fits within n, and multiplying these highest powers together.
Example: In this example we will follow the above explained approach.
JavaScript
function sieve(n) {
let isPrime = Array(n + 1).fill(true);
isPrime[0] = isPrime[1] = false;
for (let i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (let j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
return isPrime.map((prime, index) => prime ? index : false).filter(Boolean);
}
function highestPowerOfPrimeUnderN(prime, n) {
let power = prime;
while (power * prime <= n) {
power *= prime;
}
return power;
}
function smallestDivisibleByFirstN(n) {
const primes = sieve(n);
let result = 1;
primes.forEach(prime => {
result *= highestPowerOfPrimeUnderN(prime, n);
});
return result;
}
let n = 10;
console.log(`The smallest number that is divisible by the first ${n} numbers is:
${smallestDivisibleByFirstN(n)}`);
OutputThe smallest number that is divisible by the first 10 numbers is:
2520
Using Array.from and Recursion
This approach leverages recursion to compute the LCM of a list of numbers. By breaking down the problem into smaller subproblems, it recursively calculates the LCM of two numbers at a time.
Example: In this example, we will use a recursive approach to find the smallest number divisible by the first n numbers.
JavaScript
function calculateGCD(a, b) {
return b === 0 ? a : calculateGCD(b, a % b);
}
function calculateLCM(a, b) {
return (a * b) / calculateGCD(a, b);
}
function recursiveLCM(arr) {
if (arr.length === 2) {
return calculateLCM(arr[0], arr[1]);
} else {
const lastElement = arr.pop();
return calculateLCM(lastElement, recursiveLCM(arr));
}
}
function smallestDivisibleRecursiveLCM(n) {
const numbers = Array.from({ length: n }, (_, i) => i + 1);
return recursiveLCM(numbers);
}
console.log(smallestDivisibleRecursiveLCM(10));
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read