TExcelTAD
Home › Foundations of Algorithm Analysis › Factorials, Stirling and the Iterated Logarithm

Factorials, Stirling and the Iterated Logarithm

Two functions sit at the far ends of the growth ladder. The factorial n!n! grows faster than any exponential cnc^n, and it is the number of orderings of nn items, so it appears in every analysis that reasons about permutations, from the sorting lower bound to random shuffles. The iterated logarithm lg⁡∗n\lg^* n grows so slowly that it is at most 5 for every input that fits in the universe, yet it is not a constant, and it shows up in the running times of real data structures. Between them, this lesson also meets the Fibonacci numbers and the golden ratio, the classic example of exponential growth with an irrational base.

The ladder so far, from Polynomials, Exponentials and Logarithms: 1≪lg⁡lg⁡n≪lg⁡n≪n≪n≪nlg⁡n≪n2≪2n1 \ll \lg \lg n \ll \lg n \ll \sqrt{n} \ll n \ll n \lg n \ll n^2 \ll 2^n.

Factorials and two easy bounds

n!=1⋅2⋯nn! = 1 \cdot 2 \cdots n, with 0!=10! = 1. Two crude bounds already decide most questions:

  • Upper: each of the nn factors is at most nn, so n!≤nnn! \le n^n.
  • Lower: the largest ⌈n/2⌉\lceil n/2 \rceil factors are each at least n/2n/2, so n!≥(n/2)n/2n! \ge (n/2)^{n/2}.

Taking logarithms of both bounds gives

n2lg⁡n2≤lg⁡(n!)≤nlg⁡n\frac{n}{2} \lg \frac{n}{2} \le \lg(n!) \le n \lg n

and the left side is at least 14nlg⁡n\frac{1}{4} n \lg n once n≥4n \ge 4 (because lg⁡(n/2)=lg⁡n−1≥12lg⁡n\lg(n/2) = \lg n - 1 \ge \frac{1}{2} \lg n when lg⁡n≥2\lg n \ge 2). Therefore

lg⁡(n!)=Θ(nlg⁡n)\lg(n!) = \Theta(n \lg n)

This one line is the reason no comparison sort can beat nlg⁡nn \lg n: a comparison sort must distinguish all n!n! orderings, and kk yes/no comparisons can distinguish at most 2k2^k of them, so it needs k≥lg⁡(n!)k \ge \lg(n!). The next course, Sorting and Order Statistics, proves this in full.

python · try it yourself
import math

print(f"{'n':>8} {'lg(n!)':>12} {'n lg n':>12} {'ratio':>7}")
for n in [4, 16, 64, 256, 1024, 4096]:
    lg_fact = math.log2(math.factorial(n))
    print(f"{n:>8} {lg_fact:12.1f} {n * math.log2(n):12.1f} {lg_fact / (n * math.log2(n)):7.3f}")
       n       lg(n!)       n lg n   ratio
       4          4.6          8.0   0.573
      16         44.3         64.0   0.691
      64        296.0        384.0   0.771
     256       1684.0       2048.0   0.822
    1024       8769.0      10240.0   0.856
    4096      43250.0      49152.0   0.880

The ratio climbs toward 1, but slowly. The crude bounds only promise a ratio between 14\frac{1}{4} and 1; Stirling's formula explains the slow approach.

Stirling's approximation

n!=2πn(ne)n(1+Θ ⁣(1n))n! = \sqrt{2\pi n} \left( \frac{n}{e} \right)^n \left( 1 + \Theta\!\left( \frac{1}{n} \right) \right)

The relative error is about 112n\frac{1}{12n}, so the approximation is already within 1 percent at n=10n = 10 and within 0.1 percent at n=100n = 100. The program checks both claims: the ratio of n!n! to the formula tends to 1, and 12n12n times the excess tends to 1 as well.

python · try it yourself
import math

def stirling(n):
    return math.sqrt(2 * math.pi * n) * (n / math.e) ** n

print(f"{'n':>4} {'n! / Stirling':>14} {'12n (ratio - 1)':>16}")
for n in [1, 2, 5, 10, 20, 50, 100, 170]:
    r = math.factorial(n) / stirling(n)
    print(f"{n:>4} {r:14.6f} {12 * n * (r - 1):16.4f}")
   n  n! / Stirling  12n (ratio - 1)
   1       1.084438           1.0133
   2       1.042207           1.0130
   5       1.016784           1.0070
  10       1.008365           1.0038
  20       1.004175           1.0020
  50       1.001668           1.0008
 100       1.000834           1.0004
 170       1.000490           1.0002

Taking the logarithm of Stirling's formula gives a sharper statement than Θ(nlg⁡n)\Theta(n \lg n):

lg⁡(n!)=nlg⁡n−nlg⁡e+12lg⁡n+O(1)\lg(n!) = n \lg n - n \lg e + \tfrac{1}{2} \lg n + O(1)

The second term, about 1.44 n1.44\,n, is what keeps the ratio in the first table well below 1 for so long.

Consequences worth remembering:

  • n!=o(nn)n! = o(n^n): the ratio n!/nnn!/n^n is about 2πn e−n\sqrt{2\pi n}\,e^{-n}, which tends to 0.
  • n!=ω(cn)n! = \omega(c^n) for every constant cc: the factor (n/e)n(n/e)^n eventually beats cnc^n once n>cen > ce.
  • lg⁡(n!)=Θ(nlg⁡n)\lg(n!) = \Theta(n \lg n), as shown above.

Fibonacci numbers and the golden ratio

The Fibonacci numbers F0=0F_0 = 0, F1=1F_1 = 1, Fi=Fi−1+Fi−2F_i = F_{i-1} + F_{i-2} grow exponentially with base

ϕ=1+52≈1.61803,ϕ^=1−52≈−0.61803\phi = \frac{1 + \sqrt{5}}{2} \approx 1.61803, \qquad \hat{\phi} = \frac{1 - \sqrt{5}}{2} \approx -0.61803

the two roots of x2=x+1x^2 = x + 1. The closed form is Fi=(ϕi−ϕ^i)/5F_i = (\phi^i - \hat{\phi}^i)/\sqrt{5}, and since ∣ϕ^∣<1\lvert \hat{\phi} \rvert < 1 the second term is smaller than 12\frac{1}{2} in absolute value, so FiF_i is simply ϕi/5\phi^i/\sqrt{5} rounded to the nearest integer. Hence Fi=Θ(ϕi)F_i = \Theta(\phi^i). Fibonacci numbers bound the height of AVL trees and the number of steps of Euclid's algorithm. The closed form is derived in Linear Recurrences; here is a numerical check.

python · try it yourself
import math

phi = (1 + math.sqrt(5)) / 2
a, b = 0, 1
mismatches = 0
for i in range(71):
    if round(phi**i / math.sqrt(5)) != a:
        mismatches += 1
    if i in (10, 20, 40, 70):
        print(f"F_{i} = {a}, ratio F_(i+1)/F_i = {b / a:.10f}")
    a, b = b, a + b
print("mismatches with round(phi^i / sqrt 5) for i <= 70:", mismatches)
print("phi =", round(phi, 10))
F_10 = 55, ratio F_(i+1)/F_i = 1.6181818182
F_20 = 6765, ratio F_(i+1)/F_i = 1.6180339985
F_40 = 102334155, ratio F_(i+1)/F_i = 1.6180339887
F_70 = 190392490709135, ratio F_(i+1)/F_i = 1.6180339887
mismatches with round(phi^i / sqrt 5) for i <= 70: 0
phi = 1.6180339887

The ratio of consecutive Fibonacci numbers converges to ϕ\phi, quickly. The check stops at i=70i = 70 because beyond that floating point no longer holds enough digits; exact big integers would be needed.

Functional iteration

Write f(i)(n)f^{(i)}(n) for ff applied ii times: f(0)(n)=nf^{(0)}(n) = n and f(i)(n)=f(f(i−1)(n))f^{(i)}(n) = f(f^{(i-1)}(n)). For example, with f(n)=2nf(n) = 2n, f(i)(n)=2inf^{(i)}(n) = 2^i n. Do not confuse lg⁡(i)n\lg^{(i)} n, the logarithm applied ii times, with lg⁡in\lg^i n, the ii-th power of the logarithm: lg⁡(2)256=lg⁡8=3\lg^{(2)} 256 = \lg 8 = 3, while lg⁡2256=64\lg^2 256 = 64.

The iterated logarithm

lg⁡∗n=min⁡{ i≥0:lg⁡(i)n≤1 }\lg^* n = \min \{\, i \ge 0 : \lg^{(i)} n \le 1 \,\}

lg⁡∗n\lg^* n counts how many times you must take lg⁡\lg before the value drops to 1 or below. Each extra unit of lg⁡∗\lg^* needs a tower of twos one level higher:

nn lg⁡∗n\lg^* n
1 0
2 1
3, 4 2
5 to 16 3
17 to 65536 4
65537 to 2655362^{65536} 5

2655362^{65536} has 19,729 decimal digits, far more than the roughly 108010^{80} atoms in the observable universe. So for every input an algorithm will ever see, lg⁡∗n≤5\lg^* n \le 5. It still tends to infinity, so it is not O(1)O(1); it is o(lg⁡lg⁡⋯lg⁡n)o(\lg \lg \cdots \lg n) for any fixed number of logarithms.

python · try it yourself
import math

def lg_star(n):
    count = 0
    while n > 1:
        n = math.log2(n)   # exact for powers of two, works on huge ints
        count += 1
    return count

for n in [1, 2, 3, 4, 5, 16, 17, 65536, 65537, 2**65536]:
    label = "2^65536" if n == 2**65536 else str(n)
    print(f"lg*({label}) = {lg_star(n)}")
print("decimal digits of 2^65536:", math.floor(65536 * math.log10(2)) + 1)
lg*(1) = 0
lg*(2) = 1
lg*(3) = 2
lg*(4) = 2
lg*(5) = 3
lg*(16) = 3
lg*(17) = 4
lg*(65536) = 4
lg*(65537) = 5
lg*(2^65536) = 5
decimal digits of 2^65536: 19729

Where does such a slow function come from? An algorithm that repeatedly replaces a problem of size nn by one of size lg⁡n\lg n runs for lg⁡∗n\lg^* n rounds. The union-find structure with union by rank and path compression, covered in the Data Structures course of this track, has an amortized cost per operation bounded by O(lg⁡∗n)O(\lg^* n) in one classic analysis and by the even slower inverse Ackermann function in the tight one.

Test yourself

What is lg⁡∗65536\lg^* 65536?

  1. 16
  2. 4
  3. 5
  4. 2

Which pair of crude bounds proves lg⁡(n!)=Θ(nlg⁡n)\lg(n!) = \Theta(n \lg n)?

  1. 2n≤n!≤3n2^n \le n! \le 3^n
  2. (n/2)n/2≤n!≤nn(n/2)^{n/2} \le n! \le n^n
  3. n≤n!≤n2n \le n! \le n^2
  4. n!≤2nn! \le 2^n

Stirling's formula has relative error about 112n\frac{1}{12n}. Roughly how far off is it at n=50n = 50?

  1. About 17 percent
  2. About 1.7 percent
  3. About 0.17 percent
  4. Exactly right

Which statement is false?

  1. n!=o(nn)n! = o(n^n)
  2. n!=ω(10n)n! = \omega(10^n)
  3. Fn=Θ(ϕn)F_n = \Theta(\phi^n)
  4. lg⁡∗n=O(1)\lg^* n = O(1)