I am confused on the following:
In the following trivial code:
for (int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
for(int k = j + 1; k < n; k++) {
//some code here
}
}
}
I know that the complexity is N^3
. But I am confused on some details.
The outer loop is executed N times.
The inner loop I thought that it was executed N*(N-1) times but when I tested with a small example of n=5
it is executed actually N*(N-1)/2
times. And the inner most loop I am lost on how the exact number of times it is executed. I originally thought that it is executed N(N-1)(N-2)
but this is wrong again by using a small n the numbers don't work out.
So my question is:
1) Can someone help me understand how the exact complexity is calculated on this trivial example?
2) What is the usual process? Do we select some small numbers and try to derive a formula or what?