查詢一個數字的所有質因子——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]

更新於: 2020 年 9 月 15 日

1K+ 次瀏覽

啟動你的職業生涯

完成課程認證

開始
廣告