How would you write a non-recursive algorithm to compute n!
?
public double factorial(int n) {
double result = 1;
for(double i = 2; i<=n; ++i) {
result *= i;
}
return result;
}
Rewrite the recursive solution as a loop.
I would use memoization. That way you can write the method as a recursive call, and still get most of the benefits of a linear implementation.
long fact(int n) {
long x = 1;
for(int i = 1; i <= n; i++) {
x *= i;
}
return x;
}