Complexity of recursive factorial program

前端 未结 4 623
余生分开走
余生分开走 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:37

    Assuming you're talking about the most naive factorial algorithm ever:

    factorial (n):
      if (n = 0) then return 1
      otherwise return n * factorial(n-1)
    

    Yes, the algorithm is linear, running in O(n) time. This is the case because it executes once every time it decrements the value n, and it decrements the value n until it reaches 0, meaning the function is called recursively n times. This is assuming, of course, that both decrementation and multiplication are constant operations.

    Of course, if you implement factorial some other way (for example, using addition recursively instead of multiplication), you can end up with a much more time-complex algorithm. I wouldn't advise using such an algorithm, though.

提交回复
热议问题