TExcelTAD
Home › Foundations of Algorithm Analysis › Comparing Growth Rates

Comparing Growth Rates

The previous lessons built a toolbox: definitions, limits, and the standard functions with their rules. This lesson puts it to work on the most common task in algorithm analysis, deciding which of two running times grows faster. It shows the five classic growth rates side by side, sorts a list of fourteen functions with one trick (take logarithms), turns growth rates into "how large an input can I afford", and finds the crossover point where an asymptotically faster algorithm actually starts to win.

Watch them grow

The lab plots lg⁡n\lg n, nn, nlg⁡nn \lg n, n2n^2 and 2n2^n as nn grows. Press Play. On the linear scale the vertical axis stops at n2n^2, so 2n2^n leaves the chart almost at once.

02565127681024148121620242832input size nsteps2ⁿ is off the chartlog₂ nnn log₂ nn²2ⁿ

Switch the scale to logarithmic to see all five at once. On a log scale a polynomial nkn^k becomes a curve that flattens out, while 2n2^n becomes a straight line that climbs at a constant rate.

110²10⁴10⁶10⁸10¹⁰10¹²10¹⁴10¹⁶10¹⁸1816243240485664input size nsteps (log scale)log₂ nnn log₂ nn²2ⁿ

The table gives the exact values the lab shows at a few input sizes. Doubling nn adds 1 to lg⁡n\lg n, doubles nn, a bit more than doubles nlg⁡nn \lg n, multiplies n2n^2 by 4 and squares 2n2^n.

python · try it yourself
import math

print(f"{'n':>4} {'lg n':>6} {'n':>4} {'n lg n':>7} {'n^2':>6} {'2^n':>22}")
for n in [8, 16, 32, 64]:
    print(f"{n:>4} {math.log2(n):>6.0f} {n:>4} {n * math.log2(n):>7.0f} {n * n:>6} {2**n:>22,}")
   n   lg n    n  n lg n    n^2                    2^n
   8      3    8      24     64                    256
  16      4   16      64    256                 65,536
  32      5   32     160   1024          4,294,967,296
  64      6   64     384   4096 18,446,744,073,709,551,616

Sorting functions by taking logarithms

To compare ff and gg when both are made of powers and exponentials, compare lg⁡f\lg f and lg⁡g\lg g instead. Logarithms turn exponents into factors, which are much easier to compare. The rule is:

  • If lg⁡g(n)−lg⁡f(n)→∞\lg g(n) - \lg f(n) \to \infty, then g(n)/f(n)→∞g(n)/f(n) \to \infty, so f=o(g)f = o(g).
  • If lg⁡g(n)−lg⁡f(n)\lg g(n) - \lg f(n) stays bounded, the ratio stays bounded and the two are within constant factors of each other.

Note what the rule does not say. Comparing lg⁡f\lg f and lg⁡g\lg g only up to constant factors is too weak: lg⁡(n2)=2lg⁡n=Θ(lg⁡n)\lg(n^2) = 2 \lg n = \Theta(\lg n), yet n2≠Θ(n)n^2 \ne \Theta(n). It is the difference of the logarithms that has to be examined, not their ratio.

Some disguised functions become obvious once their logarithm is written down, with L=lg⁡nL = \lg n:

Function lg⁡\lg of it So it equals
n1/lg⁡nn^{1/\lg n} 1L⋅L=1\frac{1}{L} \cdot L = 1 the constant 2
2 lg⁡n\sqrt{2}^{\,\lg n} 12L\frac{1}{2} L n\sqrt{n}
4lg⁡n4^{\lg n} 2L2L n2n^2
(lg⁡n)lg⁡n(\lg n)^{\lg n} Llg⁡LL \lg L nlg⁡lg⁡nn^{\lg \lg n}, more than any polynomial
(lg⁡n)!(\lg n)! Llg⁡L−Llg⁡e+O(lg⁡L)L \lg L - L \lg e + O(\lg L) also more than any polynomial

The program lists fourteen functions in increasing order, each through its logarithm as a formula in LL, and prints the gap lg⁡fnext−lg⁡f\lg f_{\text{next}} - \lg f between neighbours at n=216n = 2^{16}, 2642^{64}, 22562^{256} and 25122^{512}. A gap that keeps growing means the next function is strictly faster.

python · try it yourself
import math

lg = math.log2
LN2 = math.log(2)
# each function as lg f(n), written in terms of L = lg n
fns = [
    ("n^(1/lg n)",   lambda L: 1.0),
    ("sqrt(lg n)",   lambda L: 0.5 * lg(L)),
    ("lg n",         lambda L: lg(L)),
    ("lg^2 n",       lambda L: 2 * lg(L)),
    ("sqrt n",       lambda L: L / 2),
    ("n",            lambda L: L),
    ("lg(n!)",       lambda L: lg(math.lgamma(2.0**L + 1) / LN2)),
    ("n lg n",       lambda L: L + lg(L)),
    ("n^2",          lambda L: 2 * L),
    ("(lg n)!",      lambda L: math.lgamma(L + 1) / LN2),
    ("(lg n)^lg n",  lambda L: L * lg(L)),
    ("2^n",          lambda L: 2**L),
    ("n 2^n",        lambda L: 2**L + L),
    ("n!",           lambda L: math.lgamma(2.0**L + 1) / LN2),
]
Ls = [16, 64, 256, 512]
print("gap = lg f(next) - lg f(this), at n = 2^L")
print(f"{'f(n)':>12} -> {'next':<12}" + "".join(f"{'L=' + str(L):>12}" for L in Ls))
for (a, fa), (b, fb) in zip(fns, fns[1:]):
    gaps = [fb(L) - fa(L) for L in Ls]
    print(f"{a:>12} -> {b:<12}" + "".join(f"{g:12.3g}" for g in gaps))
gap = lg f(next) - lg f(this), at n = 2^L
        f(n) -> next                L=16        L=64       L=256       L=512
  n^(1/lg n) -> sqrt(lg n)             1           2           3         3.5
  sqrt(lg n) -> lg n                   2           3           4         4.5
        lg n -> lg^2 n                 4           6           8           9
      lg^2 n -> sqrt n                 0          20         112         238
      sqrt n -> n                      8          32         128         256
           n -> lg(n!)              3.86        5.97        7.99           9
      lg(n!) -> n lg n             0.136      0.0329     0.00815     0.00407
      n lg n -> n^2                   12          58         248         503
         n^2 -> (lg n)!             12.3         168    1.17e+03    2.85e+03
     (lg n)! -> (lg n)^lg n         19.7          88         364         733
 (lg n)^lg n -> 2^n             6.55e+04    1.84e+19    1.16e+77   1.34e+154
         2^n -> n 2^n                 16          64         256         512
       n 2^n -> n!              8.88e+05    1.14e+21    2.94e+79   6.83e+156

Every gap grows, with one exception: the gap from lg⁡(n!)\lg(n!) to nlg⁡nn \lg n shrinks toward 0, because the two are Θ\Theta of each other (Factorials, Stirling and the Iterated Logarithm). Two more details are worth a look. The gap from lg⁡2n\lg^2 n to n\sqrt{n} is 0 at n=216n = 2^{16}: the two functions are equal there (162=256=6553616^2 = 256 = \sqrt{65536}), and only beyond it does n\sqrt{n} pull away. And the first few gaps grow like lg⁡L=lg⁡lg⁡n\lg L = \lg \lg n, very slowly, but without bound, which is all that "strictly faster" requires.

The numbers are evidence, not proof. Each ordering is proved with the tools of Little o, Little omega and Limits: for example (lg⁡n)lg⁡n(\lg n)^{\lg n} against 2n2^n means comparing Llg⁡LL \lg L with 2L2^L, an exponential against a polynomial in LL.

What an input budget buys

Growth rates become concrete when you fix a budget of steps and ask how large an input fits. Assume, as a model, a machine that does 10910^9 basic steps per second, and take budgets of a millisecond, a second and a day. The program finds the largest nn with f(n)≤Bf(n) \le B for each budget BB by doubling and then binary search, counting nothing but the formula.

python · try it yourself
import math

def largest(f, budget):
    # largest n >= 1 with f(n) <= budget, for an increasing f
    hi = 1
    while f(hi * 2) <= budget:
        hi *= 2
    lo, hi = hi, hi * 2          # f(lo) <= budget < f(hi)
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if f(mid) <= budget:
            lo = mid
        else:
            hi = mid
    return lo

fns = [
    ("n", lambda n: n),
    ("n lg n", lambda n: n * math.log2(n)),
    ("n^2", lambda n: n * n),
    ("n^3", lambda n: n**3),
    ("2^n", lambda n: 2**n),
    ("n!", lambda n: math.factorial(n)),
]
budgets = [("1 ms: 10^6", 10**6), ("1 s: 10^9", 10**9), ("1 day: 8.64e13", 864 * 10**11)]
print(f"{'f(n)':>8}" + "".join(f"{b:>20}" for b, _ in budgets))
for name, f in fns:
    print(f"{name:>8}" + "".join(f"{largest(f, B):>20,}" for _, B in budgets))
    f(n)          1 ms: 10^6           1 s: 10^9      1 day: 8.64e13
       n           1,000,000       1,000,000,000  86,400,000,000,000
  n lg n              62,746          39,620,077   2,110,372,739,876
     n^2               1,000              31,622           9,295,160
     n^3                 100               1,000              44,208
     2^n                  19                  29                  46
      n!                   9                  12                  16

Two rows are missing because their answers are absurd: with lg⁡n\lg n steps, a second handles n=2109n = 2^{10^9}, and with n\sqrt{n} steps it handles n=1018n = 10^{18}. The table shows the real meaning of the growth rates:

  • For nn, a budget 86,400 times larger (a day instead of a second) buys an input 86,400 times larger. For nlg⁡nn \lg n it buys about 53,000 times more, because the logarithm grows too.
  • For n2n^2 it buys only 86400≈294\sqrt{86400} \approx 294 times more, and for n3n^3 about 44 times more.
  • For 2n2^n a day buys 17 more items than a second, because each extra item doubles the cost. For n!n! it buys 4.

A faster computer is a bigger budget. If machines become 1,000 times faster (the step from the first column to the second), an nlg⁡nn \lg n algorithm handles inputs over 600 times larger, while a 2n2^n one handles 10 more items.

Crossover points

Asymptotics compare functions for large nn. For small nn the constants decide. Suppose algorithm A costs 100 nlg⁡n100\,n \lg n steps and algorithm B costs n2n^2 steps. B is cheaper while n<100lg⁡nn < 100 \lg n, and the program finds where that stops.

python · try it yourself
import math

a = lambda n: 100 * n * math.log2(n)
b = lambda n: n * n
last_b = max(n for n in range(2, 5000) if b(n) <= a(n))
print(f"n^2 <= 100 n lg n for 2 <= n <= {last_b}")
for n in [10, 100, last_b, last_b + 1, 10**4, 10**6]:
    print(f"  n = {n:>7}: 100 n lg n = {a(n):>16,.0f}   n^2 = {b(n):>16,}")

small = [n for n in range(1, 50) if 2**n < n**3]
print(f"2^n < n^3 exactly for n = {small[0]}..{small[-1]}")
n^2 <= 100 n lg n for 2 <= n <= 996
  n =      10: 100 n lg n =            3,322   n^2 =              100
  n =     100: 100 n lg n =           66,439   n^2 =           10,000
  n =     996: 100 n lg n =          992,016   n^2 =          992,016
  n =     997: 100 n lg n =          993,157   n^2 =          994,009
  n =   10000: 100 n lg n =       13,287,712   n^2 =      100,000,000
  n = 1000000: 100 n lg n =    1,993,156,857   n^2 = 1,000,000,000,000
2^n < n^3 exactly for n = 2..9

Up to n=996n = 996 the quadratic algorithm is cheaper, and at n=996n = 996 the two costs differ by less than one step. From n=997n = 997 on, the nlg⁡nn \lg n algorithm wins, and the gap grows quickly: at n=106n = 10^6 it is 500 times cheaper. Similarly an exponential 2n2^n algorithm beats an n3n^3 one for 2≤n≤92 \le n \le 9, then loses forever.

This is not just theory. Library sorts are hybrids for this reason: Python's built-in sort (Timsort) sorts short runs with binary insertion sort before merging them, and many quicksort implementations switch to insertion sort below a small cutoff. The asymptotically better algorithm takes over only where it is actually better.

Test yourself

Which function grows fastest?

  1. n10n^{10}
  2. (lg⁡n)lg⁡n(\lg n)^{\lg n}
  3. 2lg⁡n2^{\sqrt{\lg n}}
  4. nlg⁡5nn \lg^5 n

lg⁡f(n)=Θ(lg⁡g(n))\lg f(n) = \Theta(\lg g(n)). What can you conclude?

  1. f=Θ(g)f = \Theta(g)
  2. f=O(g)f = O(g)
  3. Nothing about ff against gg: for example lg⁡(n2)=Θ(lg⁡n)\lg(n^2) = \Theta(\lg n) but n2≠Θ(n)n^2 \ne \Theta(n)
  4. f=o(g)f = o(g)

With a budget of 10910^9 steps, an n2n^2 algorithm handles n=31622n = 31622. Roughly what does a budget of 101110^{11} steps allow?

  1. n=3,162,200n = 3{,}162{,}200
  2. n≈316,000n \approx 316{,}000
  3. n≈31,700n \approx 31{,}700
  4. n≈63,000n \approx 63{,}000

Algorithm A takes 100 nlg⁡n100\,n \lg n steps and B takes n2n^2. Which is true?

  1. A is always faster because nlg⁡n=o(n2)n \lg n = o(n^2)
  2. B is faster for 2≤n≤9962 \le n \le 996 and A from n=997n = 997 on
  3. B is always faster because 100 is a big constant
  4. They cross only at n=100n = 100