问题
int i, j;
for(i=0; i<n*n; i++)
{
if(i % n == 0)
for(j=0; j<n; j++)
x++;
else
x--;
}
I'm new to runtime analysis so I'm just checking my answer on here to see if I have the right idea.
I have to find a tight runtime bound for that segment and give a reasoning.
I came up with O(n²).
My reasoning behind it is because it runs the first for loop n² times. It only runs the second for loop if i is divisible by n.
Is this okay or am I completely wrong in my analysis?
回答1:
The outer loop runs n² times. Every n-th run (so n runs in total), it starts another loop, which runs n times. That amounts to n² + n * n which equals 2n² which is a runtime of O(n²).
来源:https://stackoverflow.com/questions/18656270/runtime-analysis