1

I have a recursive function. And i’m looking for what is the time complexity ? Here is the function

 public static int f7(int N){
         if (N==1) return 0;
         return 1 + f7(N/2);
   }
2
  • If N is 10, it will 3 times recursive call. Am i right? Commented Nov 17, 2019 at 17:40
  • Seem it will be O(log(n)) Commented Nov 17, 2019 at 17:40

2 Answers 2

2

First, we come up with a recurrence for this function:

T(1) = 1
T(n) = T(n/2) + 1

This is a recurrence that we can plug into the master theorem, which will give us Θ(log n) as an answer.

Sign up to request clarification or add additional context in comments.

Comments

1

Assume that when N=1, the call takes a time units, and when N is a power of 2, it takes b time units, not counting the recursive call.

Then

T(1) = a
T(2^n) = T(2^(n-1)) + b.

This can be seen as an ordinary linear recurrence

S(0) = a
S(n) = S(n-1) + b = S(n-2) + 2b = … = S(0) + nb = a + nb,

or

T(N) = a + Lg(N) b

where Lg denotes the base-2 logarithm.

When N is not a power of 2, the time is the same as for the nearest inferior power of 2.

The exact formula for all N is

T(N) = a + [Lg(N)] b.

Brackets denote the floor function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.