Question

I am trying to figure out what the big o estimate of the following nested for loop is.

for(int i = 10; i to 100; i++){
 for(int j = 1; j to i; j++){
  for(int k = 1; k to j; k++){
   s=s+i+j;
  }
 }
}

I was thinking that the two inner loops run n times but I am unsure about the first loop.

What would the Big O estimate be for this code?

Was it helpful?

Solution

Technically the complexity is O(1) because 100 is a constant and thus the number of operations is always the same. If the author assumed that 100 is a parameter and can be some variable, i.e.

int n = 100; //or read it somewhere
for (int i = 10; i < n; ++i) {
    .... 
}

then the complexity is O(n^3). The first cycle body is executed n - 10 times which is O(n), the second cycle's body is executed from n - 10 times to once, which is again O(n), and the same can be stated for the innermost cycle, thus giving us O(n^3).

Article useful for understanding the big O notation: Big O notation

OTHER TIPS

the complexity is O(1) since there is no n here and the number of ops can be calculated exactly

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top