Search code examples
theorycomplexity-theorybig-o

Big O complexity of simple for not always linear?


I'm sure most of you know that a nested loop has O(n^2) complexity if the function input size is n

for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
...
}
}

I think that this is similar, by a analogous argument, but i'm not sure can anyone confirm?

for(int i = 0, max = n*n; i < max; i++{
...
}

If so i guess that there is some kinds of code whose big O mapping is not immediately obvious besides recursion and subroutines.


Solution

  • Your basic simple loop is always O(m) where m is the upper bound on the iterations. But your m is really n*n, so it's O(n^2).