它来自家庭作业,但我要求一种通用方法。
计算以下代码的最坏情况运行时间。
int sum = 0;
for (int i = 0; i*i < N; i++)
for (int j = 0; j < i*i; j++)
sum++;
答案是 N^3/2,谁能帮我解决这个问题?
有没有通用的方法来计算这个?
This is what I thought:
when i = 0, sum++ will be called 0 time
when i = 1, sum++ will be called 1 time
when i = 2, sum++ will be called 4 times
...
when i = i, sum++ will be called i^2 times
so the worst time will be
0 + 1 + 4 + 9 + 16 + ... + i^2
但接下来呢?我在这里迷路了...