Created
May 14, 2013 17:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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