How would you write a non-recursive algorithm to compute n!
?
I love the pythonic solution to this:
def fact(n): return (reduce(lambda x, y: x * y, xrange(1, n+1)))
in pseudocode
ans = 1
for i = n down to 2
ans = ans * i
next
int fact(int n){
int r = 1;
for(int i = 1; i <= n; i++) r *= i;
return r;
}
fac = 1 ;
for( i = 1 ; i <= n ; i++){
fac = fac * i ;
}
Iterative:
int answer = 1;
for (int i = 1; i <= n; i++){
answer *= i;
}
Or... using tail recursion in Haskell:
factorial x =
tailFact x 1
where tailFact 0 a = a
tailFact n a = tailFact (n - 1) (n * a)
What tail recursion does in this case is uses an accumulator to avoid piling on stack calls.
Reference: Tail Recursion in Haskell
Recursively using JavaScript with caching.
var fc = []
function factorial( n ) {
return fc[ n ] || ( ( n - 1 && n != 0 ) &&
( fc[ n ] = n * factorial( n - 1 ) ) ) || 1;
}