- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Smallest number that is divisible by first n numbers in JavaScript
We are required to write a JavaScript function that takes in a number, say n. The function should find and return the smallest possible number that is exactly divisible by all numbers from 1 to n.
Example
Following is the code −
const smallestDivisible = (num) => { let i, n = 1; const largestPower = (n, num) => { let p, e = 2, largest = n; while ((p = Math.pow(n, e)) <= num) { largest = p; e += 1; } return largest; } const isPrime = n => { let i, num = Math.ceil(Math.sqrt(n)); for (i = 3; i <= num; i += 2) { if (n % i === 0) { return false; } } return true; } for (i = 3; i <= num; i += 2) { if (isPrime(i)) { n *= largestPower(i, num); } } return n * largestPower(2, num); } console.log(smallestDivisible(20));
Output
Following is the output on console −
232792560
- Related Articles
- Smallest possible number divisible by all numbers from 1 to n in JavaScript
- Generating a random number that is divisible by n in JavaScript
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- A number is divisible by $12$. By what other numbers will that number be divisible?
- Find the smallest square number that is divisible by each of the numbers 5, 15 and 45.
- Count n digit numbers divisible by given number in C++
- PHP program to find the sum of first n natural numbers that are divisible by a number ‘x’ or a number ‘y’
- Find the smallest number that is exactly divisible by 18 , 25 and 40
- Check if product of first N natural numbers is divisible by their sum in Python
- Largest N digit number divisible by given three numbers in C++
- Greatest number divisible by n within a bound in JavaScript
- Sum which is divisible by n in JavaScript
- Finding a pair that is divisible by some number in JavaScript
- Sum of first N natural numbers which are divisible by X or Y
- Find the smallest 4 digit number that is exactly divisible by 36, 40, and 45.

Advertisements