Reputation: 251
I want to write power recursive function that it's analyse is o(n): This is my idea is it true?? Or if the analyse of this code is not o(n) can anyone help me to change it to make it better?? thanks in advance
power(int x , int n)
{
if(n==0)
return 1;
else
return x*power(x,n-1);
}
Upvotes: 1
Views: 547
Reputation: 2238
This is O(n) time because you are counting down from the input n to where n is 0.
Upvotes: 1
Reputation: 1102
You are calling "k" times your function and its upper bound matches with its lower bound. So i think it's Theta(k)
Upvotes: 1
Reputation: 5637
You are calling your function recursively "k+1" times. Example for power(10,3), you make the following function calls
power(10,3) -
power(10,2) | k+1 times
power(10,1) |
power(10,0) -
Thus the complexity is O(k) and not O(n) !
Upvotes: 1
Reputation: 178253
This method is O(k), not O(n), because it will perform k
recursive calls. Additionally, the base case k
being 0
should return 1
, not n
.
Upvotes: 1
Reputation: 85779
There are two problems:
After that, the code should work. It will behave in linear time for the power, so it will be O(k).
Upvotes: 1