I am somewhat familiar with Big O notation, however I came across an explanation of Big O notation that I cant quite get.
int foo(int n) {
int p = 1; -------------->c1 x 1
int i = 1; ------------->c1 x 1
while (i < n) { ------------>c2 x n
int j = 1; ------------------->c1 x (n - 1)
while (j < i) { ----------->c2 x ((1/2)n^2 - (3/2)n + 2)
p = p * j; -------------->(c1 + c3) x ((1/2)n^2 - (3/2)n + 1)
j = j + 1; -------------->(c1 + c4) x ((1/2)n^2 - (3/2)n + 1)
}
i = i + 1; ------------------->(c1 + c4) x (n - 1)
}
return p; ---------------------->c5 x 1
}
(c1 + 1/2*c2 + 1/2*c3 + 1/2*c4)n^2 + (-c1 – 1/2*c2 – 3/2*c3 – 1/2*c4)n + (2*c1 + 2*c2 + c3 + c5)
I understand that this algo will turn out to be n^2 because of the nested loops and the reduction of constants and low order terms in the resulting equation. However, what I do not understand is how the rhs of the “x” is derived for example ((1/2)n^2 – (3/2)n + 1). Any insights into this will be most appreciated, I really need to understand the core concepts of Big O notation. Thanks.
There are n-1 iterations of cycle while(i < n)
Innner cycle will be executed 0, 1, 2, 3,..n-2 times – this is arithmetic progression, and its sum is (n-2)(n-1)/2 = (1/2) n^2 – (3/2) n + 1