I’m preparing for an exam and these are some of problems from last year’s tests. The task is to calculate both exact and asymptotic complexity. How would you solve it? Universally, if possible.
for ( i = j = 0; i < n; j ++ ) {
doSomething ();
i += j / n;
j %= n;
}
for ( i = 0; i < 2 * n; i += 2 )
for ( j = 1; j <= n; j <<= 1 )
if ( j & i )
doSomething ();
for (i = 0; i < 2*n; i++) {
if ( i > n )
for (j = i; j < 2 * i; j ++ ) doSomething();
else
for (j = n; j < 2 * n; j ++ ) doSomething();
}
Thanks in advance
My solution for the third loop is
so it is in
O(n^2)given thatdoSomething()has a constant timeand that
iandjare integers.The second term (
[ n^2 +n ] *D) is fairly easy.The loop
gets called while
i <= nso it will be calledn+1times, since it starts from 0.The loop
for (j = n; j < 2 * n; j ++ )callsdoSomething()ntimes, so we have(n+1)*n*D = [n^2+n] *D. I assume thatdoSomething()has a constant time which is equal toDThe first term is a little bit more complex.
gets called when
i>nso it will be calledn-1times.The loop calls
doSomething()i times.The first time it gets called
n+1, the second time ´n+2´ and so on until it is2n-1which is equal ton + (n-1).So we get a sequence likes this
{n+1, n+2, n+3, ... , n+(n-1)}.If we sum up the sequence we get
n-1timesnand the sum1+2+3+...+ (n-1).The last term can be solved with the “Gaußsche Summenformel” (sorry I don’t have the English name for it but you can see the formula in the German wiki link) so it is equal to
((n-1)*n)/2So the first term is
(n-1) * n + ((n-1)*n)/2 *DAnd the last term is therefor the if statement which is called
2*n*I, whereIis the time to execute the If statement.