# JavaScript 中最快的阶乘程序

Sahil Bhosale 2023年10月12日

## 在 JavaScript 中使用递归的阶乘程序

``````let start, end;
start = new Date().getTime();

for (var i = 0; i < 10000; i++) recursionFactorial(1000)

function recursionFactorial(num) {
if (num === 0)
return 1;
else
return num * recursionFactorial(num - 1);
}

end = new Date().getTime();

console.log(end);
``````

``````1627808767415
``````

## 在 JavaScript 中使用迭代的阶乘程序

`iterationFactorial()` 函数中，我们最初将计数器设置为 `1`，然后使用 for 循环通过增加 `counter` 变量来查找因子。最后，我们返回 `counter` 变量的值。

``````let start2, end2;
start2 = new Date().getTime();

for (var i = 0; i < 10000; i++) iterationFactorial(1000);

function iterationFactorial(num) {
var counter = 1;
for (var i = 2; i <= num; i++) counter = counter * i;
return counter;
}

end2 = new Date().getTime();

console.log(end2);
``````

``````1627808727136
``````

## JavaScript 中最快的阶乘程序

``````let res1 = end - start;
let res2 = end2 - start2;

console.log('res1: ' + res1 + ' res2: ' + res2)
``````

``````res1: 1626 res2: 27
``````

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.