I'm trying to derive the simplified asymptotic running time in Theta() notation for the two nested loops below.
For i <-- 1 to n do
j <-- 1
while j*j <= i
j = j+1
For i <-- 1 to n
j <-- 2
while j <= n
j = j*j
I have been trying to solve this using the summation method but not really getting the right answer. The picture below shows my attempts at the problem, I was able to get (n^3/2) for the first algorithm, however, I wasn't sure how to proceed with the second algorithm.
Best Answer
First algorithm
We iterate
n
times in the outer loop. For every iterationi
, the inner loop iterates from 1 tosqrt(i)
, sosqrt(i)
times. So the total number of iterations is:I spare you and me the maths, but the result can be approximated by the integral of
√n
which is(2/3)*n^(3/2)
. For very big numbers, this is mainly driven by the strongest polynomial factor, so the the complexity isO(n^(3/2))
.Second alogrithm
If there's a typo and the while should be <= i
We iterate
n
times in the outer loop. For every iterationi
, the inner loop iteratesk
times, where k is such that2^k>i
.k
can easily be determined aslog2(i)
solog(i)/log(2)
.so this time we have a total number of iteration of
For the order of magnitude, we can ignore the constant coefficient and just look at the sum. Again, sparing you (and me!) the math, the sum is
log(n!)
which is approximated bynlog(n)
If there is no typo and it's really <= n
Then you perform
n
times the same inner loop which is made oflog(n)/log(2)
iterations, so here the number of iteration isSo it's exactly
O(nlog(n))