First algorithm
We iterate n
times in the outer loop. For every iteration i
, the inner loop iterates from 1 to sqrt(i)
, so sqrt(i)
times. So the total number of iterations is:
n
∑ √i
i=1
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 is O(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 iteration i
, the inner loop iterates k
times, where k is such that 2^k>i
. k
can easily be determined as log2(i)
so log(i)/log(2)
.
so this time we have a total number of iteration of
1 n
---- . ∑ log(i)
log2 i=1
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 by nlog(n)
If there is no typo and it's really <= n
Then you perform n
times the same inner loop which is made of log(n)/log(2)
iterations, so here the number of iteration is
1 n 1
---- . ∑ log(n) = ---- . n log(n)
log2 i=1 log2
So it's exactly O(nlog(n))