Home > Net >  Time complexity of nested loop?
Time complexity of nested loop?

Time:05-08

I'm not very familiar with Big O notation. I'm wondering does the time complexity of the nested loop always be n^2? For example the following function, the inner loop runs 100 times per loop, does it be considered as n times as well? What's the time complexity of this function?

int abc(int x) {
    for (int i=0; i<x; i  ) {
         for (int j=0; j<100; j  ) {
             push to stack;
        }
    }
    return 0;
}

CodePudding user response:

Big O notation shows how the performance scales with input size. The inner loop is not at all affected by any change in input size, so it is not reflected in the time complexity: this code is O(N), where N is the size of x.

CodePudding user response:

If a statement is executed 100 times or 1000 times, the total cost for that statement is O(1).

In the given program, the outer loop has x iterations, and each iteration costs O(1). So the total cost is O(x).

  • Related