简体   繁体   中英

How to calculate Time Complexity for a given algorithm

i, j, N, sum is all integer type. N is input.

( Code1 )

i = N;

while(i > 1)
{
    i = i / 2;
    for (j = 0; j < 1000000; j++)
    {
       sum = sum + j;
    }
}

( Code2 )

sum = 0;
d = 1;
d = d << (N-1);
for (i = 0; i < d; i++)
{
    for (j = 0; j < 1000000; j++)
    {
        sum = sum + i;
    }
}

How to calculate step count and time complexity for a Code1, Code2?

to calculate the time complexity try to understand what takes how much time, and by what n are you calculating.

if we say the addition ("+") takes O(1) steps then we can check how many time it is done in means of N .

the first code is dividing i in 2 each step, meaning it is doing log(N) steps. so the time complexity is

 O(log(N) * 1000000)= O(log(N))

the second code is going form 0 to 2 in the power of n-1 so the complexity is:

 O(s^(N-1) * 1000000)=  O(2^(N-1))

but this is just a theory, because d has a max of 2^32/2^64 or other number, so it might not be O(2^(N-1)) in practice

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