Algorithm running time

北慕城南 提交于 2019-12-13 09:55:08

问题


What would the running time be? I got O(n^2)

`cin >> n;
 min = 2*n;
 max = (n+3)*10;

for(int i=0; i<1000; i++)
    for(int j =0; j<n; j++)
         for(int k = min; k< max;k++)
            p = f+c+m

`


回答1:


No matter what outer loop runs 1000 times..so the complexity ~O(n^2). [innermost runs 10n+30-2n = 8n+30 times and loop with variable j runs n times..]




回答2:


The number of times p is computed is:

   1000 * n * (max - min)
=  1000 * n * ((n + 3)*10 - 2*n)
=  1000 * n * (10*n + 30 - 2*n)
=  1000 * n * (8*n + 30)
=  8000 * n^2 + 30000 * n

Yes, it is O(n^2).



来源:https://stackoverflow.com/questions/33293998/algorithm-running-time

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