I have following piece of code:
int sum = 0; for (int i = 1; i <= N; i++) for (int j = 1; j <= N; j++) for (int k = 1; k <= N; k = k*2) for (int h = 1; h <= k; h++) sum++;
So I'v calculated how much does each cycle executes and then whole script, and I think I might be wrong for the last one.
1. N 2. N 3. 1 + log2N( means log N to the base 2) 4. N
So the total execution amount of inner cycle would be N^3 * (1 + log2N).
Am I right? How I can transform this statement?
I have another solution which seems monstrous:
1. N 2. N 3. LOG2(N) + 1 4. 2^(LOG2(2N)) - 1
So total cycles amount would be
n^2 * (LOG2(N) + 1) * 2^(LOG2(2N)) - 1.
Which transforms to n^2 order of growth.
I wrote simple test app to check my assumption.
it seems that third cycle is already calculated for some reason is fourth one. At least this is the result of test app. I threw away
(LOG2(N) + 1).
As the result of several transformations I have following equation for total amount of sum++ calls:
N*N*(2*N - 1) = 2 * N^3 - N^2 ~ N^3