Complexity of recursive factorial program

前端 未结 4 592
余生分开走
余生分开走 2020-12-23 10:17

What\'s the complexity of a recursive program to find factorial of a number n? My hunch is that it might be O(n).

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 10:27

    The time-complexity of recursive factorial would be:

    factorial (n) {    
        if (n = 0) 
            return 1
        else
            return n * factorial(n-1)
    }
    

    So,

    The time complexity for one recursive call would be:

    T(n) = T(n-1) + 3   (3 is for As we have to do three constant operations like 
                     multiplication,subtraction and checking the value of n in each recursive 
                     call)
    
         = T(n-2) + 6  (Second recursive call)
         = T(n-3) + 9  (Third recursive call)
         .
         .
         .
         .
         = T(n-k) + 3k
         till, k = n
    
         Then,
    
         = T(n-n) + 3n
         = T(0) + 3n
         = 1 + 3n
    

    To represent in Big-Oh notation,

    T(N) is directly proportional to n,

    Therefore, The time complexity of recursive factorial is O(n). As there is no extra space taken during the recursive calls,the space complexity is O(N).

提交回复
热议问题