简体   繁体   中英

Find time complexity of a nested loop

For the loop below,

int sum = 0;
for (int i = 1; i < N; i *= 2)
    for (int j = 0; j < N; j++)
        sum++;

what is the time complexity and how should I think? My guess is that the outer loop runs a total of log(N) . The inner loop runs N times. Therefore, the time complexity should be Nlog(N) .

Am I correct?

Thanks in advance.

For the first loop, the number of iterations is equal to log2(N) , as i is doubled every iteration.

For each iteration of the first loop, the second loop runs for N times.

Therefore overall time complexity = (log2(N) * N) , where the function log2(x) = log(x) to the base 2.

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