I recently started playing with algorithms from this princeton course, and I noticed the following pattern
O (N)
double max = a[0]; for (int i = 1; i < N; i++) if (a[i] > max) max = a[i];
O (N ^ 2)
for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) if (a[i] + a[j] == 0) cnt++;
O (N ^ 3)
for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) for (int k = j+1; k < N; k++) if (a[i] + a[j] + a[k] == 0) cnt++;
The general pattern here is that as nesting in the cycle increases, the exponent also increases. Can I assume that if I have a 20-cycle, my complexity will be 0 (N ^ 20)?
PS: Please note that 20 is just a random number that I chose, and yes, if you put 20 loops in your code, something is wrong with you.
source share