Runtime analysis

╄→尐↘猪︶ㄣ 提交于 2020-01-16 00:19:16

问题


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 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!