在JavaScript中分解数字
我们需要编写一个以正整数作为唯一参数的JavaScript函数。该函数应构造并返回一个包含所有数字的数组,这些数组将精确地划分输入数字。
例如-
如果输入号码是-
const num = 12;
那么输出应该是-
const output = [1, 2, 3, 4, 6, 12];
示例
以下是代码-
const findFactors = (num = 1) => {
let half = Math.floor(num / 2);
const res = [1]; //1将成为每个解决方案的一部分。
let i, j;
num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for (i; i <= half; i += j) {
if(num % i === 0){
res.push(i);
};
};
res.push(num);
return res;
};
console.log(findFactors(12));输出结果
以下是控制台上的输出-
[ 1, 2, 3, 4, 6, 12 ]