JavaScript中数字的素数数组
我们需要编写一个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]
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语