我写了一个简单的代码,试图理解BigOh符号评估。 基于链接:
big-o-how-do-you-calculate-approximate-it
我的代码在这里[这只是随机的,没有具体原因我为什么最终得到这个代码]:
public class ScratchPad {
/**
* @param args
*/
public static void main(String[] args) {
int[] data = {1,2,3,4,5,6};
int result = 0;
int N = 6; //From 0 through 6
for (int i =0;i<N;i++)
{
result += data[i];
}
System.out.println("Final result: "+result);
}
}
基于运行此代码段的实际结果的N和f(N)系列是:
Values of N: 0, 1, 2, 3, 4, 5, 6
Values of f(N): 0, 1, 3, 6, 10, 15, 21
我的问题:
下面的f(N)是什么公式?像2*N^2
或N+N*1-1
等。
我尝试了其中的一些方程式并没有成功。
答案 0 :(得分:4)
f(N)是小于或等于N的所有整数之和。
f(N) = N + f(N-1)
= N + N-1 + N-2 + ... + 2 + 1
= N*(N+1) / 2