简体   繁体   English

三重嵌套循环的Big-O

[英]Big-O of Triple Nested Loop

What would the Time complexity (Big-O) of such an algorithm be 这种算法的时间复杂度(Big-O)是多少

for (int i = 1; i < n; i++) {
    for (int j = 1; j < i; j++) {
        for (int k = 1; k < j; k++) {
            x++;
        }
    } 
}

Is it exponential? 它是指数的吗?

Assuming the input is n 假设输入为n

Thanks! 谢谢!

for (int i = 1; i < n; i++) { // O(n) time complexity
    for (int j = 1; j < i; j++) { // O(n) time complexity
        for (int k = 1; k < j; k++) { // O(n) time complexity
            x++;
        }
    } 
}

The first loop does n number of computations. 第一个循环执行n次计算。 Your second loop continues to go until i reaches its condition, which is n , and k continues until j reaches its condition. 您的第二个循环继续进行,直到i达到其条件n为止,并且k继续直到j达到其条件为止。 Each loop is reaching the same condition, n 每个循环都达到相同的条件, n

So, each loop has a time complexity of O(n) ; 因此,每个循环的时间复杂度为O(n) because they are nested, you multiply each n, which results in a total time complexity of O(n^3) 因为它们是嵌套的,所以将每个n相乘,这将导致总时间复杂度为O(n^3)

每个循环为O(n)因此总体为O(n^3)

It will be 0(n^3) complexity as there are 3 loops with 0(n) complexity. 这将是0(n ^ 3)复杂度,因为有3个循环的复杂度为0(n)。 As your number of loop increases, the time complexity of your method keeps on multiplying. 随着循环次数的增加,方法的时间复杂度不断增加。 So you have n loops in your program, then time complexity of your program will be 0(n^n). 因此,您的程序中有n个循环,那么程序的时间复杂度将为0(n ^ n)。 You can refer to this http://www.programmerinterview.com/index.php/data-structures/big-o-notation/ for more reference. 您可以参考http://www.programmerinterview.com/index.php/data-structures/big-o-notation/以获得更多参考。

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

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