4

What would be the time complexity for this, will it be O(​​​​logn)?

fun(int n) {
    if (n < 2)
        return 1;
    int counter = 0;
    for (int i = 1; i <= 8; i++)
        fun(n / 2);
    for (int i = 1; i <= Math.pow(n, 3); i++)
        counter++;
}
2
  • Why would it be log n? You've got a for-loop up to n-cubed in the function. Commented Jul 19, 2020 at 20:35
  • What does fun return? int or void? Anyway it doesn't compile. Commented Jul 19, 2020 at 23:11

1 Answer 1

8

The complexity of the function is:

T(n) = n^3 + 8*T(n/2)
  • n^3 comes from the last loop, which is going from 1 to n^3
  • 8*T(n/2) from calling fun(n/2) 8 times (in the first loop)

To find the complexity, one can use master theorem with: a = 8, b = 2, f(n) = n^3

Using case 2:

log_2(8) = 3, and indeed f(n) is in Theta(n^3), giving this function complexity of O(n^3*logn).

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

1 Comment

The variable counter is not used, so optimizer may remove the last loop.

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.