Can anyone help me to calculate and explain me time complexity of this algorithm :
function mystery(n)
r := 0
for i := 1 to n − 1 do
for j := i + 1 to n do
for k := 1 to j do
r := r + 1
return(r)
Can anyone help me to calculate and explain me time complexity of this algorithm :
function mystery(n)
r := 0
for i := 1 to n − 1 do
for j := i + 1 to n do
for k := 1 to j do
r := r + 1
return(r)
I have no idea how to make sigma character on StackOverflow but it will be:
Sigma(i=1; n-1)Sigma(j=i+1; n)Sigma(k=1;j)1=Sigma(i=1; n-1)Sigma(j=i+1;n)j
you can simplify the inner Sigma by:
Sigma(j=i+1; n)j = Sigma(j=1;n)j - Sigma(j=1;i)j = n(n-1)/2 - i(i-1)/2=n^2-i^2+n-i
then you have:
Sigma(i=1; n-1)n^2-i^2+n-i
It will be O(n^3)
but get my answer more as a tip than solution