2

CODE:

void fun(int n){
    if(n>2){
        for(int i=0;i<n;i++){
            j=0;
            while(j<n){
                cout<<j;
                j++;
            }
        }
        fun(n/2);
    }
}

Here's what I think: The recursive part is running log(n) times ? and during each recursive call, the for loop will run n^2 times, with n changing to half in each recursive call. So is it n^2 + (n^2)/4 + (n^2)/16 + ... + 1?

3 Answers 3

3

You are right, so the big(O) is n^2 since the sum of the series n^2 + (n^2)/4 + (n^2)/16 + ... + 1 never exceeds 2n^2

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

1 Comment

it could/would still be in O(n^2) even if it exceeded 2n^2.
2

The number of writes to cout is given by the following recurrence:

T(N) = N² + T(N/2).

By educated guess, T(N) can be a quadratic polynomial. Hence

T(N) = aN²+bN+c = N² + T(N/2) = N² + aN²/4+bN/2+c.

By identification, we have

3a/4 = 1
b/2 = 0
c = c.

and

T(N) = 4N²/3 + c.

With T(2)= 0,

T(N) = 4(N²-4)/3

which is obviously O(N²).

Comments

0

This is simple mathematics. The complexity is n^2 + (n^2)/4 + (n^2)/16 + ... + 1. It is (n² * (1 + 1/4+ ...)) . And the maths says that the infinite serie converges to 4/3 (the formula is: 1 / (1 - 1/4)).

It gives actually O(n2).

1 Comment

Thank you for your help!

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.