I know there is many similar questions about the Big Oh notation, but this example is quite interesting and not trivial:
int sum = 0;
for (int i = 1; i <= N; i = i*2)
for (int j = 0; j < i; j++)
sum++;
The outer loop will iterate lg(N) times, but what with inner loop? And what is T(N) for all the operations?
I can see only 3 posibilities :
- T(N) = lg(N) * 2^N
- T(N) = log(N) * (N-1)
- T(N) = N
My opinion – T(N) = N – but it is just my intuition from observations value of sum variable when N was multiplied many times – sum was almost equal to 2N, which gives us N.
Basically I do not know how to count it. Please help me with this task and explain the solution – it is quite important for me.
Thanks
The inner loop iterates the last time max. N. Before the last run it iterates N/2. If you sum it up N + N/2 + N/4 + N/8 This add up to 2*N. And that’s all as you counted all runs. T(N) = N