Can anyone explain what the time complexity is for this algorithm?
for (i = 1; i <= n; i++){
for(j = 1; j <= n; j += i) { // note: not j++
printf("Iteration %d : %d\n", i, j);
}
}
The printf
in the inner loop is called exactly ceil(n) + ceil(n/2) + ceil(n/3) + ... ceil(n/n)
times. To get rid of ceil
, we know that ceil(y/n)
is bounded above by y/n + 1
, so we know that the number of executions is >= n + n/2 + n/3 ... n/n
but is < n + 1 + n/2 + 1 + n/3 + 1 + n/4 + 1... + n/n + 1
. The former can be factored to n(1 + 1/2 + 1/3 + 1/4 ... 1/n)
and the latter can be refactored into to n(1 + 1/2 + 1/3 + 1/4 ... 1/n) + n
.
The latter factor is of the first addend to infinity is the the harmonic series, which diverges. The sum of the first k
terms from the Wikipedia page is known to be bounded:
which means that 1 + 1/2 + 1/3 + 1/4 ... 1/n
is Ө(ln n) = Ө(log n)
; we can give strict bounds for the number of times that printf
is called (c(n)
: n log n <= c(n) < n log n + 2n
. Since n log n
grows faster than 2n
, we can keep only the former and notice that both bounds belong to Ө(n log n)
and hence c(n)
belongs to Ө(n log n)
as well (Ө(F)
means that the function is both Ω(F)
and O(F)
).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments