Complexity of an algorithm

試著忘記壹切 提交于 2019-12-22 08:42:32

问题


I'm studying for a test and saw this question , so I did the following, is it correct?

the while loop runs at O(log3n).

the for loop runs at about O((n-(some math))*log2n) so because I have the minus symbol which is linear, I say that the whole method runs at O(nlogn), unless I'm wrong and it's something like

O((n-(n/log3n))*log2n) <- not exactly but quite, can't really figure it out.

is the minus linear here or not? if not what is the correct bigO?

public void foo (int n, int m)
{
    int i = m;
    while (i>100)
     i = i/3;
    for (int k=i; k>=0; k--)
    {
        for (int j=1; j<n; j*=2)
         System.out.print(k + "\t" + j);
        System.out.println();
    }
}

回答1:


The while loop runs in O(logm).

After the while loop has finished, i is <= 100, so the next for loop will run at most 100 times.

The inner loop will run O(logn) times, for each iteration of the outer loop. So total time is O(logm + 100*logn) = O(logm + logn).




回答2:


The first while loop runs in O(100*log_3(m)). This should be easy to see.

For the outer for loop, note that i is at most 100 (because of the previous while loop), and the inner loop is O(100*log_2(n)), so the overall asymptotic limit is O(log_3(m) + log_2(n)).



来源:https://stackoverflow.com/questions/22785650/complexity-of-an-algorithm

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