简体   繁体   中英

Time complexity with log in loop

what is the complexity of a loop which goes this

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < log(i); j++)
    {
        // do something
    }
}

According to me the inner loop will be running log(1)+log(2)+log(3)+...+log(n) times so how do i calculate its complexity?

Without doing this in a formal manner, such complexity calculations can be "guessed" using integrals. The integrand is the complexity of do_something , which is assumed to be O(1) , and combined with the interval of log N , this then becomes log N for the inner loop. Combined with the outer loop, the overall complexity is O(N log N) . So between linear and quadratic.

Note: this assumes that "do something" is O(1) (in terms of N , it could be of a very high constant of course).

So, you have a sum log(1) + log(2) + log(3) + ... + log(n) = log(n!) . By using Stirling's approximation and the fact that ln(x) = log(x) / log(e) one can get

log(n!) = log(e) * ln(n!) = log(e) (n ln(n) - n + O(ln(n)))

which gives the same complexity O(n ln(n)) as in the other answer (with slightly better understanding of the constants involved).

Lets start with log(1)+log(2)+log(3)+...+log(n) . Roughly half of the elements of this sum are greater than or equal to log(n/2) = log(n) - log(2) . Hence the lower bound of this sum is n / 2 * (log(n) - log(2)) = Omega(nlog(n)) . To get upper bound simply multiply n by the largest element which is log(n) , hence O(nlog(n)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM