算法:
for (int i = 0; i < 2*n; i += 2)
for (int j = n; j >i; j--)
foo();
我想找到调用 foo() 的次数。
# of foo() calls for the second loop as i changes:
1st loop: n - 0
2nd loop: n - 2
3rd loop: n - 4
nth loop: n - f(x); f(x) = last term +2; where f(0) = 0
Total # calls = Summation(n - f(x)) from [i = 0] to [i = n/2 (where f(x) == n)]
= Summation(n) - summation(f(x))
= (n/2)(n+n)/2 - (n/2)(0 + n)/2
= n^2/2 - n^2/4
= n^2/4
我已经完成了所有的工作,但我的方程式总是给出有点偏离的值:
当 n = 5 时:记录的 foo() 调用为 9,但我的等式给出 6。
当 n = 6 时:记录的 foo() 调用为 16,但我的等式给出 9。
我做错了什么?