-2

Consider two functions that accept as a parameter an unsigned integer and returns the number of digits of this number. One function is recursive and the other is non-recursive.

In terms of complexity , which implementation is better?

The language used is C/C++.

Here is non-recursive function:

int nbOfDigitsNR(int nb) {
int i=0
while(nb!=0){
 nb=nb/10; 
 ++i;
}
return i; // i is the number of digits 
}

the recursive function:

int nbOfDigitsNR(int nb) {
 static int i;
 if (nb!=0){
 i=i+1;
 nbOfDigitsNR(nb/10);}
 return i;
}

I suggest that the time complexity is the same: O(n), and the space complexity is different: O(n) recursive. O(1) non recursive.

Anthon
  • 69,918
  • 32
  • 186
  • 246
ZEMA
  • 9
  • 1
  • 3
  • You can use an O(1) algorithm for the number of digits: `numDigits(x) {return floor(log_10(x)+1)}` – halex Apr 26 '15 at 17:51
  • i think for time complexity both are O(n) where n is the number of iteration !!!!! – ZEMA Apr 26 '15 at 18:01
  • Show us your implementations together with your assumptions and arguments that fortify them for their complexities then we can discuss about them. We won't do your homework without your mental participation. – halex Apr 26 '15 at 18:15
  • One can't answer that question. I once wrote a compiler and it can detect left/right recursion and change it into a loop. – qwerty_so Apr 26 '15 at 19:28
  • 1
    @halex here is my suggestion , thank you for your interaction . – ZEMA Apr 26 '15 at 21:10

2 Answers2

1

Should one solution be recursive and other iterative, the time complexity should be the same, if of course this is the same algorithm implemented twice - once recursively and once iteratively.

The difference comes in terms of space complexity and how programming language, in your case C++, handles recursion.

Your example illustrates exactly that. Both functions will have the same time complexity, while recursive one will have bigger space complexity, since C++ allocates variables for each recursive call on stack.

You are correct about time and space complexities, if n represents number of digits. Should n represent integer, then replace it with lg(n).

Neithrik
  • 2,002
  • 2
  • 20
  • 33
0

Saying that a function is recursive or non-recursive doesn't tell us anything about its complexity.

It could be equal, or one of them with a lower complexity.. it entirely depends on the algorithm.

I have a blue and a gray car. Which one is faster?

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176