![]() |
VOOZH | about |
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:
Table of Content
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.
2520
Time Complexity: O(num * n)
Space Complexity: O(1)
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).
2520
Time Complexity: O(n * log(n)).
Space Complexity: O(1).
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.
The smallest number that is divisible by the first 10 numbers is: 2520
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.
2520