本文介绍了JavaScript中最快的因子函数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript中寻找一个非常快速的 factorial 函数实现。有什么建议吗?
Looking for a really fast implementation of factorial function in JavaScript. Any suggests?
推荐答案
如果你正在使用自然数字,查找表是显而易见的方法。
要实时计算任何阶乘,您可以使用缓存加速它,从而节省您之前计算过的数字。类似于:
Lookup table is the obvious way to go, if you're working with natural numbers.To calculate any factorial in real-time, you can speed it with a cache, saving the numbers you've calculated before. Something like:
factorial = (function() {
var cache = {},
fn = function(n) {
if (n === 0) {
return 1;
} else if (cache[n]) {
return cache[n];
}
return cache[n] = n * fn(n -1);
};
return fn;
})();
您可以预先计算某些值,以便加快速度。
You can precalculate some values in order to speed it even more.
这篇关于JavaScript中最快的因子函数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!