计算一个数的因数 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/5 10:20:17

我们需要编写一个 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

相关文章


有用资源