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

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

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

相关标签:
22条回答
  • 2020-12-10 12:11

    I love the pythonic solution to this:

    def fact(n): return (reduce(lambda x, y: x * y, xrange(1, n+1)))
    
    0 讨论(0)
  • 2020-12-10 12:15

    in pseudocode

    ans = 1
    for i = n down to 2
      ans = ans * i
    next
    
    0 讨论(0)
  • 2020-12-10 12:15
    int fact(int n){
        int r = 1;
        for(int i = 1; i <= n; i++) r *= i;
        return r;
    }
    
    0 讨论(0)
  • 2020-12-10 12:17
    fac = 1 ; 
    for( i = 1 ; i <= n ; i++){
       fac = fac * i ;
    }
    
    0 讨论(0)
  • 2020-12-10 12:17

    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

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

    Recursively using JavaScript with caching.

    var fc = []
    function factorial( n ) {
       return fc[ n ] || ( ( n - 1 && n != 0 ) && 
              ( fc[ n ] = n * factorial( n - 1 ) ) ) || 1;
    }
    
    0 讨论(0)
提交回复
热议问题