Skip to content

Instantly share code, notes, and snippets.

@lucasrizoli
Created May 14, 2013 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasrizoli/5577646 to your computer and use it in GitHub Desktop.
Save lucasrizoli/5577646 to your computer and use it in GitHub Desktop.
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