Finding Big-O with multiple nested loops?

五迷三道 提交于 2019-12-07 02:37:57

问题


int num = n/4;
for (int i = 1; i <= num; i++) {
    for (int j = 1; j <= n; j++) {
        for (int k = 1; k <= n; k++) {
            int count = 1;
        }
    }
}

According to the books I have read, this code should be O((n^3)/4). But apparently its not. to find the Big-O for nested loops are you supposed to multiply the bounds? So this one should be num *n *n or n/4 *n *n.


回答1:


O((n^3)/4) makes no sense in terms of big-O notation since it's meant to measure the complexity as a ratio of the argument. Dividing by 4 has no effect since that changes the value of the ratio but not its nature.

All of these are equivalent:

O(n^3)
O(n^3/4)
O(n^3*1e6)

Other terms only make sense when they include an n term, such as:

O(n^3 / log(n))
O(n^3 * 10^n)

As Anthony Kanago rightly points out, it's convention to:

  • only keep the term with the highest growth rate for sums: O(n^2+n) = O(n^2).
  • get rid of constants for products: O(n^2/4) = O(n^2).

As an aside, I don't always agree with that first rule in all cases. It's a good rule for deciding the maximal growth rate of a function but, for things like algorithm comparison(a) where you can intelligently put a limit on the input parameter, something like O(n^4+n^3+n^2+n) is markedly worse than just O(n^4).

In that case, any term that depends on the input parameter should be included. In fact, even constant terms may be useful there. Compare for example O(n+1e100) against O(n^2) - the latter will outperform the former for quite a while, until n becomes large enough to have an effect on the constatnt term.


(a) There are, of course, those who would say it shouldn't be used in such a way but pragmatism often overcomes dogmatism in the real world :-)




回答2:


From http://en.wikipedia.org/wiki/Big_O_notation you can see that constants like the 1/4 do not play a role for determining the Big-O notation. The only interesting fact is that it is n^3, thus O(N^3).




回答3:


Formally, the time complexity can be deduced like the following:




回答4:


A small technicality. Big O notation is intended to describe complexity in terms of the 'size' of the input, not the numeric value. If your input is a number, then the size of the input is the number of digits of your number. Alas, your algorithm is O(2^N^3) with N being the number of digits.

More on this topic



来源:https://stackoverflow.com/questions/766939/finding-big-o-with-multiple-nested-loops

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