我们需要编写一个以数字作为唯一输入的JavaScript函数。函数应找到最小的此类数字,该数字可被所有前n个自然数完全整除。
例如-
对于n = 4,输出应为12
因为12是可被1和2以及3和4整除的最小数字。
为此的代码将是-
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));输出结果
控制台中的输出将是-
2 12 27720 360360