JavaScript 中数字的质因数数组
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/26 9:16:17
我们需要编写一个 JavaScript 函数,该函数接受一个数字并返回一个数组,其中包含所有能够精确整除输入数字的质数。
例如,如果输入数字是 105。
那么输出应该是 −
const output = [3, 5, 7];
示例
其代码为 −
const num = 105;
const isPrime = (n) => {
for(let i = 2; i <= n/2; i++){
if(n % i === 0){
return false;
}
};
return true;
};
const findPrimeFactors = num => {
const res = num % 2 === 0 ? [2] : [];
let start = 3;
while(start <= num){
if(num % start === 0){
if(isPrime(start)){
res.push(start);
};
};
start++;
};
return res;
};
console.log(findPrimeFactors(18));
输出
控制台中的输出 −
[3, 5, 7]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

