简体   繁体   English

如何计算给定算法的时间复杂度

[英]How to calculate Time Complexity for a given algorithm

i, j, N, sum is all integer type. i,j,N,和都是整数类型。 N is input. 输入N。

( Code1 ) (代码1)

i = N;

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

( Code2 ) (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? 如何计算Code1,Code2的步数和时间复杂度?

to calculate the time complexity try to understand what takes how much time, and by what n are you calculating. 要计算时间复杂度,请尝试了解需要花费多少时间以及要计算的n数。

if we say the addition ("+") takes O(1) steps then we can check how many time it is done in means of N . 如果我们说加法(“ +”)采取O(1)步,那么我们可以用N来检查完成了多少次。

the first code is dividing i in 2 each step, meaning it is doing log(N) steps. 第一个代码在每个步骤中将i分为2,这意味着它正在执行log(N)个步骤。 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: 第二个代码以n-1的幂形式从0到2,所以复杂度是:

 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 但这只是一个理论,因为d的最大值为2 ^ 32/2 ^ 64或其他数字,所以实际上它可能不是O(2 ^(N-1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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