(since this is a longer answer, read the bolds for a summary)
Let's take your example and walk through it step-by-step, understanding the purpose behind what we are doing. We start with your function and the goal of finding its Big Oh notation:
f(n) = 6n+4
First, let O(g(n))
be the Big Oh notation we are trying to find for f(n)
. From the definition of Big Oh, we need to find a simplified g(n)
where there exists some constants c
and n0
where c*g(n) >= f(n)
is true for all n
's greater than n0
.
First, let's choose g(n) = 6n + 4
(which would yield O(6n+4)
in Big Oh). In this case we see that c = 1
and any value of n0
will meet the mathematical requirements from our definition of Big Oh, since g(n)
always equals f(n)
:
c*g(n) >= f(n)
1*(6n + 4) >= 6n + 4 //True for all n's, so we don't need to pick an n0
At this point we've met the mathematical requirements. If we stopped at O(6n+4)
, it's clear that this is no more helpful than writing f(n)
, so it would miss the true purpose of Big Oh notation: to understand the general time-complexity of an algorithm! Thus, let's move on to the next step: simplification.
First, can we simplify out of the 6n
so the Big Oh is O(4)
? No! (Exercise for the reader if they don't understand why)
Second, can we simplify out the 4
so that the Big Oh is O(6n)
? Yes! In that case, g(n) = 6n
, so:
c*g(n) >= f(n)
c*6n >= 6n + 4
At this point, let's choose c = 2
since then the left side will increase faster (by 12) than the right side (by 6) for each increment of n
.
2*6n >= 6n + 4
Now we need to find a positive n0
where the above equation is true for all n
's greater than that value. Since we already know that the left side is increasing faster than the right, all we have to do is find one positive solution. Thus, since n0 = 2
makes the above true, we know that g(n)=6n
, or O(6n)
is a potential Big Oh notation for f(n)
.
Now, can we simplify out the 6
so that the Big Oh is O(n)
? Yes! In that case, g(n) = n
, so:
c*g(n) >= f(n)
c*n >= 6n + 4
Let's pick c = 7
since the left would increase faster than the right.
7*n >= 6n + 4
We see that the above will be true for all n
's greater than or equal to n0 = 4
. Thus, O(n)
is a potential Big Oh notation for f(n)
. Can we simplify g(n)
anymore? Nope!
Finally, we've found that the simplest Big Oh notation for f(n)
is O(n)
. Why did we go through all this? Because now we know that f(n)
is linear, since it's Big Oh notation is of linear complexity O(n)
. The nice thing is that now we can compare the time-complexity of f(n)
to other algorithms! For example, we now know that f(n)
is of comparable time-complexity to the functions h(n) = 123n + 72
, i(n) = n
, j(n) = .0002n + 1234
, etc; because using the same simplification process outlined above they all have linear time-complexity of O(n)
.
Sweet!!!