I have program like this on labs
int fun( int n )
{
if (n==0) return 0;
else return fun(n-1) +1;
}
And professor say that function is O(2^n). I Can't understand why, every time I count O I get O(n)
Anybody can explain it to me ?
I have program like this on labs
int fun( int n )
{
if (n==0) return 0;
else return fun(n-1) +1;
}
And professor say that function is O(2^n). I Can't understand why, every time I count O I get O(n)
Anybody can explain it to me ?
int fun( int n )
{
if (n==0) return 0; //1 operation for the base case
else return fun(n-1) +1; //n-1 operation in total
}
we can look at it backward, lets say you are at the base case now, you will do one return 0; which is O(1), and then one level up you will return 0+1; which is also O(1). How many times are you going to return? well the answer is simple, n times, so n*1 = n => O(n). if you want to be exact, you are doing one comparison, one addition and one return each time you recurce, so that makes it 3*n - 1 in total which is still O(n)