简体   繁体   中英

two conditions inside while loop time complexity

while( varz > equipmentNum || varz == 0 );

I have this piece of code and I want to measure its time complexity, but I am confused whether it will be Big O(n) or o(n^2) since it has two conditions inside it

This depends on what is inside of the while loop, as well as what "N" represents in this example. Presuming N is "equipmentnumz" and no inner loops exist inside of the while, this is an O(n) algorithm.

By contrast, O(n)^2 would be a nested loop (eg a loop inside of another loop). Example:

while ($x < 1000): 
    while ($y < 1000): 
        y = y + 1
    x = x + 1

O(n) notation concerns itself with the behavior of how the algorithm handles increasing data sets. O(n) algorithms take exactly twice as long if the list size is doubled. The above example will take longer than twice as long if you double the list (in fact it will take many times longer). Because the iterations required are n^2, this is an O(n^2) algorithm.

What's O(n)?

O(n) algorithms scale linearly with the dataset. The following examples are both O(n).

# O(n) algorithm
while (number < 1000): 
    number = number + 1; 

# Example 2. Also O(n) 

while (number < 1000): 
    number = number * 2; 
    number = number / 2; 
    number = number + 1; 

Although the second example has more code and will take longer to execute, it will still only take exactly twice as long if you double the size of N. As a result, it is O(n), and the time required scales linearly with the size of the dataset.

The actual process of calculating O(n) is more complex than this post can adequately cover. This article has an excellent explanation with more information. ( This page may also be helpful. It explains the concept/theory behind it in much simpler terms.)

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