Why does this O (nlogn) code run time?

advertisements

This is an exercise from the course Algorithms, Part 1 on Coursera. They said the answer is O(N log N). I do not get why:

int sum = 0;
for (int i = 1; i <= N; i = i*2)
    for (int j = 1; j <= N; j = j*2)
        for (int k = 1; k <= j; k++)
            sum++;

Could anybody please tell me how many times the inner most loop is running and why the answer is O(N log N)?

Your help is greatly appreciated.

Thank you.


The outer loop runs log(N) times. The both inner loops run combined Sum_{x=1}^{log(N)} 2^x times, where each summand represents one iteration of the middle loop. Using the geometric sum formula this makes in total log(N)(1-2^(log(N)+1))/(1-2) = log(N)(2N-1) iterations, which is obviously O(N*logN)