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]

更新於: 15-Oct-2020

281 次瀏覽

開始你的 職業

透過完成課程獲得認證

開始
廣告