Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Factorial functions, one recursive and one iterative Wanted to see if there were any significant differences in performance. http://jsperf.com/factorial-recursive-v-iterative
var factorialRecursive = (function () {
// 0! = 1 just 'cause
var factorials = [ 1 ];
return function fFactorial( n ) {
if ( n < 0 ) {
// negative n! not defined
return null;
} else if ( factorials[ n ] ) {
return factorials[ n ];
} else {
factorials[ n ] = n * fFactorial( n - 1 );
return factorials[ n ];
}
};
}());
var factorialIterative = (function () {
// 0! = 1 just 'cause
var factorials = [ 1 ];
return function ( n ) {
var j = factorials.length;
if ( n < 0 ) {
// negative n! not defined
return null;
} else {
while( j <= n ) {
factorials[ j ] = j * factorials[ j - 1 ];
j += 1;
}
return factorials[ n ];
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.