Reputation:
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.
Upvotes: 7
Views: 5458
Reputation: 2977
Formally, the time complexity can be deduced like the following:
Upvotes: 0
Reputation: 882266
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:
O(n^2+n) = O(n^2)
.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 :-)
Upvotes: 16
Reputation: 156268
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.
Upvotes: -1
Reputation: 20237
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).
Upvotes: 1