We are required to write a JavaScript function that takes in a number as the only input. The function should find the smallest such number which is exactly divisible by all the first n natural numbers.
For example −
For n = 4, the output should be 12,
because 12 is the smallest number which is divisible by 1 and 2 and 3 and 4.
Example
The code for this will be −
const smallestMultiple = num => {
let res = 0;
let i = 1;
let found = false;
while (found === false) {
res += num;
while (res % i === 0 && i <= num) {
if (i === num) {
found = true;
};
i++;
};
i = 1;
};
return res;
};
console.log(smallestMultiple(2));
console.log(smallestMultiple(4));
console.log(smallestMultiple(12));
console.log(smallestMultiple(15));Output
And the output in the console will be −
2 12 27720 360360