php - Do both these factorial functions run in O(n)? -


The recursive function is defined as:

  function factrec ($ x) {If ($ X & lt; = 1) {Return $ x; } And {return $ x * factrec ($ x - 1); }}  

and iterated here:

  function filter ($ x) {$ y = $ x; While ($ y> 1) {$ x * = ($ y - 1); $ Y--; } Return $ X; }  

I had read that the body at the recursive function is O (1) and make recursive call (N-1) O (n), but for the iteration it is o ( N) as well?

Yes, both versions run in O (n) time logic for recurring version basically recursive Version is similar: the body of the loop o (1) runs in time and executes n times.

However it should be noted that the recurring version runs in O (1) space, whereas the recursive version uses the o (n) stack space (as it has a recursion depth of n).


Comments