找出数字的所有素数-JavaScript
我们需要编写一个JavaScript函数,该函数接受一个数字并返回一个精确地将输入数字相除的所有质数的数组。
例如,如果输入数字为18。
那么输出应该是-
const output = [2, 3];
示例
让我们为该函数编写代码-
const num = 18;
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));输出结果
控制台中的输出:-
[2, 3]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短