How would you write a non-recursive algorithm to calculate factorials?

后端 未结 22 887
不思量自难忘°
不思量自难忘° 2020-12-10 11:39

How would you write a non-recursive algorithm to compute n!?

相关标签:
22条回答
  • 2020-12-10 12:29
    public double factorial(int n) {
        double result = 1;
        for(double i = 2; i<=n; ++i) {
            result *= i;
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-10 12:30

    Rewrite the recursive solution as a loop.

    0 讨论(0)
  • 2020-12-10 12:30

    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.

    0 讨论(0)
  • 2020-12-10 12:32
    long fact(int n) {
        long x = 1;
        for(int i = 1; i <= n; i++) {
            x *= i;
        }
        return x;
    }
    
    0 讨论(0)
提交回复
热议问题