計數數字的因子 - JavaScript


我們需要編寫一個 JavaScript 函式,這個函式取一個數字,然後返回能整除輸入數字的數字的計數。

例如,

如果數字是 12,那麼它的因子就是,

1, 2, 3, 4, 6, 12

因此,輸出應該是 6。

示例

以下是程式碼,

const num = 12;
const countFactors = num => {
   let count = 0;
   let flag = 2;
   while(flag <= num / 2){
      if(num % flag++ !== 0){
         continue;
      };
      count++;
   };
   return count + 2;
};
console.log(countFactors(num));
console.log(countFactors(2));
console.log(countFactors(454));
console.log(countFactors(99));

輸出

以下是控制檯中的輸出,

6
2
4
6

更新於: 15-Sep-2020

387 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.