Module contents
Lesson 3 of 33Core 110 min

Divide and conquer and the master theorem

Study divide and conquer as a source of algorithms and recurrences. Prove the master theorem with recursion trees, introduce Akra-Bazzi for unequal splits, and apply these tools to Karatsuba, Strassen, closest pair and inversion counting. Conclude with the matrix multiplication exponent ω and its current state.

After this lesson you can

  • Design divide-and-conquer algorithms by identifying division, combination and base cases.
  • Prove the master theorem using a recursion tree and apply the correct case.
  • Solve unequal recurrences using Akra-Bazzi and substitution when the master theorem does not apply.
  • Implement Karatsuba and Strassen with cutoff thresholds and measure where they outperform direct methods.
  • Explain ω, its relevance to linear algebra and its current state.

Before you start

Motivation: the multiplication once believed optimal

Multiplying two nn-digit numbers by the schoolbook method takes n2n^2 single-digit products: each digit of one factor is multiplied by each digit of the other. At a Moscow seminar in 1960, Andrey Kolmogorov stated that Ω(n2)\Omega(n^2) operations were necessary, taking this as almost self-evident. Anatoly Karatsuba, then a student, later recounted finding a counterexample algorithm in less than a week, after which Kolmogorov ended the seminar. The central trick is simple: multiplying two nn-digit numbers takes only three products of n/2n/2-digit numbers rather than four. Applied recursively, the cost falls to nlog⁡23≈n1.585n^{\log_2 3} \approx n^{1.585}.

That trick illustrates the lesson’s general idea: divide a problem into subproblems of the same kind, solve them recursively, and combine their solutions. Efficient algorithms use it throughout, including mergesort, binary search, the fast Fourier transform, fast matrix multiplication and computational geometry. Every recursive algorithm raises the same question: what does it cost? The answer is a recurrence. Two tools for solving one are the recursion tree, which gives intuition, and the master theorem, which turns that intuition into a recipe.

This lesson covers:

  • Anatomy of divide and conquer and why correctness follows by strong induction.
  • Recursion trees and the master theorem, with proof and limitations, including what it misses and how Akra-Bazzi covers it.
  • Karatsuba for integers and Strassen for matrices: the same trick of replacing a product with several sums. Strassen opens a still-unresolved question about the matrix-multiplication exponent ω\omega.
  • Geometry: closest pair and Voronoi and Delaunay diagrams.
  • Inversion counting, applied to comparing rankings.

Anatomy of divide and conquer

Costs use asymptotic notation. Mergesort, improving on the Θ(n2)\Theta(n^2) of elementary sorts to Θ(nlog⁡n)\Theta(n\log n), is the textbook example. It divides the list in two (a=b=2a = b = 2), recursively sorts both halves and merges them in linear time (f(n)=Θ(n)f(n) = \Theta(n)), giving T(n)=2T(n/2)+Θ(n)T(n) = 2T(n/2) + \Theta(n). Binary search, with a=1a = 1, b=2b = 2 and f(n)=Θ(1)f(n) = \Theta(1), is a degenerate case solving only one half. The table lists this lesson’s algorithms and their recurrences; the last two columns preview results to prove.

Algorithmaabbf(n)f(n)T(n)T(n)
Binary search1211Θ(log⁡n)\Theta(\log n)
Mergesort, inversion counting22nnΘ(nlog⁡n)\Theta(n \log n)
Closest pair of points22nnΘ(nlog⁡n)\Theta(n \log n)
Schoolbook block multiplication42nnΘ(n2)\Theta(n^2)
Karatsuba32nnΘ(n1.585)\Theta(n^{1.585})
Block matrix multiplication, 8 products82n2n^2Θ(n3)\Theta(n^3)
Strassen72n2n^2Θ(n2.807)\Theta(n^{2.807})

Correctness: strong induction

Proving a divide-and-conquer algorithm correct is almost always strong induction on input size. The base case is checked directly for n≤n0n \le n_0. The inductive step assumes the algorithm solves all smaller instances than nn correctly, including the aa subinstances, and proves their combined solutions solve the larger instance. The combination phase contains the main substance. In mergesort, the invariant says merging sorted halves gives a sorted permutation of the original; in Karatsuba, the cross term recovered by subtraction is exactly x1y0+x0y1x_1 y_0 + x_0 y_1; for closest pair, the best pair crossing the dividing line is retained. Each algorithm requires proving its combination step.

The recursion tree

Expanding the recurrence (unrolling and substitution) and drawing a recursion tree gives intuition. With n=bLn = b^L, the root performs f(n)f(n) work and creates aa children, each a subproblem of size n/bn/b. Level ii has aia^i nodes, each with subproblem size n/bin/b^i and local cost f(n/bi)f(n/b^i). The tree has L=log⁡bnL = \log_b n internal levels and aL=alog⁡bn=nlog⁡baa^L = a^{\log_b n} = n^{\log_b a} leaves, each with constant cost. Summing by level,

T(n)=∑i=0L−1aif ⁣(nbi)⏟niveles internos+Θ ⁣(nlog⁡ba)⏟hojas.T(n) = \underbrace{\sum_{i=0}^{L-1} a^i f\!\left(\frac{n}{b^i}\right)}_{\text{niveles internos}} + \underbrace{\Theta\!\big(n^{\log_b a}\big)}_{\text{hojas}}.

The number log⁡ba\log_b a is the critical exponent throughout this lesson: it controls the growth of the leaf count. Compare three rates. Node count is multiplied by aa at each level; each subproblem’s size is divided by bb, so if f(n)=ncf(n) = n^c, each node’s cost is divided by bcb^c. Total level cost is multiplied by a/bca/b^c when descending a level. This determines which work dominates:

  • If a/bc>1a/b^c > 1, or c<log⁡bac < \log_b a, cost grows downward and the last level dominates: the leaves.
  • If a/bc=1a/b^c = 1, or c=log⁡bac = \log_b a, all levels cost the same and total cost is one level’s cost times the number of levels.
  • If a/bc<1a/b^c < 1, or c>log⁡bac > \log_b a, cost decreases downward and the root dominates.
InteractiveRecursion tree explorer
… through level 9 and the leavesopacity = level weightlevel 0level 0: 1 × f(n/1)1 024level 1level 1: 3 × f(n/2)1 536level 2level 2: 9 × f(n/4)2 304level 3level 3: 27 × f(n/8)3 456level 4level 4: 81 × f(n/16)5 184level 5level 5: 243 × f(n/32)7 776level 6level 6: 729 × f(n/64)11 664level 7level 7: 2 187 × f(n/128)17 496level 8level 8: 6 561 × f(n/256)26 244level 9level 9: 19 683 × f(n/512)39 366leavesleaves: 59 049 × 159 049
  • cost of an internal level
  • cost of the leaves

Dominates: the leaves. Bars are linear relative to the most expensive level (outlined); T(n)T(n) is 1.75·10⁵ for nn = 1 024.

Examples
Recurrence
3
Reduction factor bb
1.00
Logarithmic factor in ff
10
log⁡ba\log_b a1.585
Master theorem case1
SolutionΘ ⁣(n1.585)\Theta\!\left(n^{1.585}\right)
Ratio between levels a/bca/b^c1.500
Weight at root0.6 %
Weight at leaves33.7 %
Set aa, bb and f(n)=nc(log⁡n)kf(n) = n^c (\log n)^k. The upper diagram is the tree, with each level's opacity showing its weight; bars show total cost per level including leaves. Start with Karatsuba and select «Ir a la frontera». How is work distributed when c=log⁡bac = \log_b a? Lower and raise cc: when does weight shift from leaves to root? With factor 1/log⁡n1/\log n at the boundary, the master theorem no longer decides.

The figure makes the pattern visible. In mergesort and closest pair, all levels cost the same, nn, giving nn times the number of levels, nlog⁡nn \log n. In Karatsuba, a=3a = 3, b=2b = 2 and c=1<1.585c = 1 < 1.585, bars grow downward and leaves outweigh all other levels: T=Θ(n1.585)T = \Theta(n^{1.585}). When the root dominates, for example a=2a = 2, b=2b = 2 and c=2c = 2, lower-level costs form a decreasing geometric series and initial combining work determines the order.

The master theorem

The tree also supports a proof. Turn the three observations into a theorem.

Three observations before the proof. First, case 2 with k≥0k \ge 0 is the usual form in recent editions of Cormen, Leiserson, Rivest and Stein; earlier editions gave only k=0k = 0. Second, the ε>0\varepsilon > 0 assumptions in cases 1 and 3 are polynomial: ff must be below or above nc⋆n^{c^\star} by a factor nεn^\varepsilon; a logarithmic factor is insufficient. Third, the theorem has gaps, discussed after the proof.

Proof

Work with n=bLn = b^L. The tree gives exactly

T(n)=Θ(nc⋆)+∑j=0L−1ajf(n/bj).T(n) = \Theta\big(n^{c^\star}\big) + \sum_{j=0}^{L-1} a^j f(n/b^j).

Study the sum SS in each case, writing nc⋆=aLn^{c^\star} = a^L as follows from aL=bLc⋆a^L = b^{L c^\star}.

Case 1. By hypothesis, there is a constant CC with f(m)≤C mc⋆−εf(m) \le C\,m^{c^\star - \varepsilon} for large mm. Then ajf(n/bj)≤C aj(n/bj)c⋆−ε=C nc⋆−ε(a/bc⋆−ε)j=C nc⋆−ε (bε)ja^j f(n/b^j) \le C\,a^j (n/b^j)^{c^\star - \varepsilon} = C\,n^{c^\star - \varepsilon} \big(a/b^{c^\star - \varepsilon}\big)^j = C\,n^{c^\star - \varepsilon}\,(b^{\varepsilon})^j because a=bc⋆a = b^{c^\star}. This geometric series has ratio bε>1b^\varepsilon > 1:

S≤C nc⋆−εbεL−1bε−1=O(nc⋆−ε nε)=O(nc⋆),S \le C\,n^{c^\star - \varepsilon} \frac{b^{\varepsilon L} - 1}{b^{\varepsilon} - 1} = O\big(n^{c^\star - \varepsilon}\, n^{\varepsilon}\big) = O\big(n^{c^\star}\big),

using bεL=nεb^{\varepsilon L} = n^\varepsilon. Small-size terms, for which ff is not bounded this way, sum to at most a constant times aLa^L. Including leaves gives T(n)=Θ(nc⋆)T(n) = \Theta(n^{c^\star}).

Case 2. With f(m)=Θ(mc⋆log⁡km)f(m) = \Theta(m^{c^\star} \log^k m), the level jj term is aj(n/bj)c⋆log⁡k(n/bj)⋅Θ(1)=Θ(nc⋆log⁡k(n/bj))a^j (n/b^j)^{c^\star} \log^k(n/b^j) \cdot \Theta(1) = \Theta\big(n^{c^\star} \log^k (n/b^j)\big) because ajb−jc⋆=1a^j b^{-j c^\star} = 1. With i=L−ji = L - j the logarithm is log⁡(bi)=ilog⁡b\log(b^{i}) = i \log b, and

S=Θ(nc⋆∑i=1Lik)=Θ(nc⋆Lk+1),S = \Theta\Big(n^{c^\star} \sum_{i=1}^{L} i^k\Big) = \Theta\big(n^{c^\star} L^{k+1}\big),

since ∑i=1Lik\sum_{i=1}^{L} i^k lies between L2 (L/2)k\tfrac{L}{2}\,(L/2)^k and L⋅LkL \cdot L^k for k≥0k \ge 0. Because L=log⁡bnL = \log_b n, we obtain S=Θ(nc⋆log⁡k+1n)S = \Theta(n^{c^\star} \log^{k+1} n), dominating leaves Θ(nc⋆)\Theta(n^{c^\star}). For k=0k = 0, this is the sum of LL copies of nc⋆n^{c^\star}.

Case 3. Applying regularity jj times gives ajf(n/bj)≤γjf(n)a^j f(n/b^j) \le \gamma^j f(n) while sizes n/bj−1n/b^{j-1} are large. Levels below a constant size contribute O(aL)=O(nc⋆)O(a^L) = O(n^{c^\star}), as in case 1. Thus S≤f(n)∑j≥0γj+O(nc⋆)=f(n)/(1−γ)+O(nc⋆)=O(f(n))S \le f(n) \sum_{j \ge 0} \gamma^j + O(n^{c^\star}) = f(n)/(1 - \gamma) + O(n^{c^\star}) = O(f(n)). Also S≥f(n)S \ge f(n) from term j=0j = 0, so S=Θ(f(n))S = \Theta(f(n)). Leaves contribute Θ(nc⋆)=O(f(n))\Theta(n^{c^\star}) = O(f(n)) because f(n)=Ω(nc⋆+ε)f(n) = \Omega(n^{c^\star + \varepsilon}) and do not change the result. ■\qquad\blacksquare

∎

This proof formalizes the recursion tree as an increasing geometric series in case 1, a repeated constant in case 2, or a decreasing geometric series in case 3. When nn is not a power of bb, bound TT between consecutive powers using the monotonicity of TT in the examples of interest, or invoke Akra-Bazzi. Floor and ceiling effects change none of the three conclusions.

What the theorem does not cover

The theorem is inconclusive in the following situations.

  • ff falls between cases without polynomial separation. If f(n)=nc⋆/log⁡nf(n) = n^{c^\star}/\log n (k=−1k = -1), it is not O(nc⋆−ε)O(n^{c^\star - \varepsilon}) and does not satisfy case 2 with k≥0k \ge 0. Summing levels gives ∑i=1L1/i≈ln⁡L\sum_{i=1}^{L} 1/i \approx \ln L, or T(n)=Θ(nc⋆log⁡log⁡n)T(n) = \Theta(n^{c^\star} \log\log n). If k<−1k < -1, the sum converges and T(n)=Θ(nc⋆)T(n) = \Theta(n^{c^\star}).
  • Regularity fails. Case 3’s condition does not follow from f=Ω(nc⋆+ε)f = \Omega(n^{c^\star + \varepsilon}) for arbitrary functions. With a=b=2a = b = 2 (c⋆=1c^\star = 1), define ff on powers of 2 by f(2L)=4Lf(2^L) = 4^L if LL is even and f(2L)=21.5Lf(2^L) = 2^{1.5L} if LL is odd. Thus f(n)f(n) oscillates between n2n^2 and n1.5n^{1.5}. f(n)≥n1.5=nc⋆+0.5f(n) \ge n^{1.5} = n^{c^\star + 0.5} holds, but for odd LL, 2f(n/2)=2(n/2)2=n2/22f(n/2) = 2(n/2)^2 = n^2/2 exceeds f(n)=n1.5f(n) = n^{1.5} once n>4n > 4: no γ<1\gamma < 1 works. Case 3’s conclusion is false: for odd LL, T(n)≥2f(n/2)=n2/2T(n) \ge 2f(n/2) = n^2/2 is not O(f(n))=O(n1.5)O(f(n)) = O(n^{1.5}). If f(n)=ncf(n) = n^c with c>c⋆c > c^\star, regularity follows automatically with γ=a/bc<1\gamma = a/b^c < 1, so it rarely needs separate checking in practice.
  • Unequal subproblem sizes, such as T(n)=T(n/3)+T(2n/3)+nT(n) = T(n/3) + T(2n/3) + n, sizes not exact fractions of nn, or a number of subproblems depending on nn.

The last case has a more general tool.

Akra-Bazzi: unequal subproblems

The hi(x)h_i(x) terms absorb floors and ceilings: ⌊x/2⌋=x/2−{x/2}\lfloor x/2 \rfloor = x/2 - \{x/2\} is x/2x/2 plus bounded error. This justifies moving from powers of bb to general nn. Exponent pp is unique because p↦∑aibipp \mapsto \sum a_i b_i^p is strictly decreasing: each bipb_i^p decreases with pp since bi<1b_i < 1.

The master theorem is the special case ai=aa_i = a, bi=1/bb_i = 1/b, with k=1k = 1 term of multiplicity aa. Equation a b−p=1a\,b^{-p} = 1 gives p=log⁡ba=c⋆p = \log_b a = c^\star. For g(u)=ucg(u) = u^c, the integral is ∫1xuc−p−1 du=(xc−p−1)/(c−p)\int_1^x u^{c - p - 1}\,\mathrm{d}u = (x^{c-p} - 1)/(c - p) if c≠pc \neq p and ln⁡x\ln x if c=pc = p. Thus:

  • if c<pc < p, the integral converges to a constant and T=Θ(xp)T = \Theta(x^p), case 1;
  • if c=pc = p, the integral is ln⁡x\ln x and T=Θ(xplog⁡x)T = \Theta(x^p \log x), case 2;
  • if c>pc > p, the integral has order xc−px^{c-p} and T=Θ(xc)T = \Theta(x^c), case 3 without a separate regularity check.

The Akra-Bazzi proof is more technical than the master theorem’s, using induction with a comparison function correcting xpx^p. We use it as a tool in the next example, which appears in the next lesson’s linear-time median-of-medians selection algorithm.

Master substitution, or «guess and check by induction», because Akra-Bazzi gives only the order, not the constant, and sometimes the inductive claim must be strengthened. With T(n)=2T(n/2)+1T(n) = 2T(n/2) + 1, hypothesis T(n)≤c nT(n) \le c\,n does not close the induction, but T(n)≤c n−1T(n) \le c\,n - 1 does. Case T(n)=T(n/3)+T(2n/3)+nT(n) = T(n/3) + T(2n/3) + n has p=1p = 1 because 1/3+2/3=11/3 + 2/3 = 1, so T(n)=Θ(nlog⁡n)T(n) = \Theta(n \log n). The tree is unbalanced but levels weigh equally until the shorter branch ends, as in case 2.

Karatsuba: three products instead of four

Let xx and yy be nn-digit integers, with even nn, and B=10n/2B = 10^{n/2}. Split each in half: x=x1B+x0x = x_1 B + x_0, y=y1B+y0y = y_1 B + y_0, with x1,x0,y1,y0x_1, x_0, y_1, y_0 of n/2n/2 digits. Then

xy=x1y1 B2+(x1y0+x0y1) B+x0y0.x y = x_1 y_1\,B^2 + (x_1 y_0 + x_0 y_1)\,B + x_0 y_0.

These are four half-size products, and recurrence T(n)=4T(n/2)+Θ(n)T(n) = 4T(n/2) + \Theta(n), where Θ(n)\Theta(n) accounts for additions and shifts, gives Θ(n2)\Theta(n^2) by case 1: no improvement. Karatsuba’s algorithm observes that the middle term x1y0+x0y1x_1 y_0 + x_0 y_1 need not be computed as two products. Compute three:

P1=x1y1,P2=x0y0,P3=(x1+x0)(y1+y0),P_1 = x_1 y_1, \qquad P_2 = x_0 y_0, \qquad P_3 = (x_1 + x_0)(y_1 + y_0),

and obtain the cross term by subtraction: x1y0+x0y1=P3−P1−P2x_1 y_0 + x_0 y_1 = P_3 - P_1 - P_2. This is Gauss’s trick for multiplying complex numbers with three real products instead of four. Now T(n)=3T(n/2)+Θ(n)T(n) = 3T(n/2) + \Theta(n), with c⋆=log⁡23≈1.585>1c^\star = \log_2 3 \approx 1.585 > 1: case 1,

T(n)=Θ(nlog⁡23)=Θ(n1.585).T(n) = \Theta\big(n^{\log_2 3}\big) = \Theta(n^{1.585}).

For n=2kn = 2^k digits, recursive calls form a ternary tree of depth kk with 3k3^k single-digit products at the leaves, versus 4k=n24^k = n^2 for schoolbook multiplication. With 64 digits there are 36=7293^6 = 729 products versus 40964096; with 1024 digits, 59 04959\,049 versus 1 048 5761\,048\,576.

Sum x1+x0x_1 + x_0 can have n/2+1n/2 + 1 digits due to carry, so recursive calls are no longer exactly half-size. Akra-Bazzi absorbs this through terms hih_i without changing the order. The figure uses a carry-free variant: P3=(x1−x0)(y0−y1)P_3 = (x_1 - x_0)(y_0 - y_1) gives x1y0+x0y1=P1+P2+P3x_1 y_0 + x_0 y_1 = P_1 + P_2 + P_3 with operands still at most n/2n/2 digits long, at the cost of tracking the sign.

InteractiveKaratsuba step by step
5. Recombine and check
P1B2P_1 B^21081 6010 0000 0000
(P1+P2+P3) B(P_1+P_2+P_3)\,B0000 5509 9784 0000
P2P_20000 0000 2453 4638
sum1082 1520 2237 4638
x⋅yx \cdot y directly1082 1520 2237 4638

They match: the algorithm is correct in this case.

27 leaves: single-digit products (base case)
Selected node: 12345678×8765432112345678 \times 87654321 with 8 digits is solved using three 4-digit products.
  • high parts x1y1x_1 y_1
  • low parts x0y0x_0 y_0
  • differences (x1−x0)(y0−y1)(x_1 - x_0)(y_0 - y_1)
Operands
Root steps
5 / 5
Call tree
3
Single-digit products, Karatsuba27
Single-digit products, schoolbook64
Saving58 %
Selected call (original product)8 digits
Use two 8-digit numbers. Step through splitting, three recursive products, subtraction to recover the cross term, and recombination checked against direct multiplication. Below, each product branches into three calls, colored by high, low and difference terms. Expand levels and compare single-digit products, 3k3^k versus 4k4^k. Select a node to see its operands. Try 99999999×9999999999999999 \times 99999999, where the differences are zero.

From integers to polynomials and the FFT

The argument does not require BB to be a power of 10. If x(t)=x1(t) tm+x0(t)x(t) = x_1(t)\,t^{m} + x_0(t) are polynomials, the trick is identical with coefficients instead of digits. It underlies polynomial and medium-size integer multiplication in computer algebra libraries. Generalizing, Toom-Cook splits each factor into rr pieces and evaluates polynomials at 2r−12r - 1 points, obtaining the product with 2r−12r - 1 products of size n/rn/r, giving Θ(nlog⁡r(2r−1))\Theta(n^{\log_r (2r - 1)}): with r=3r = 3, nlog⁡35≈n1.465n^{\log_3 5} \approx n^{1.465}. More splitting brings the exponent toward 1 but increases addition and interpolation constants. The next step is the FFT for evaluation and interpolation at roots of unity, giving FFT convolution in Θ(nlog⁡n)\Theta(n \log n) operations and integer multiplication in O(nlog⁡nlog⁡log⁡n)O(n \log n \log\log n) (Schönhage and Strassen, 1971). Harvey and van der Hoeven reached O(nlog⁡n)O(n \log n) in 2019, conjectured optimal. CPython uses schoolbook multiplication up to about 70 internal 30-bit digits, then Karatsuba; specialized libraries use Toom-Cook and FFT at larger sizes.

Strassen: seven products instead of eight

Multiplying two A,B∈Rn×n\mat{A}, \mat{B} \in \R^{n \times n} matrices using the definition of matrix multiplication requires n3n^3 products and n2(n−1)n^2(n - 1) additions. Split the matrices into n/2×n/2n/2 \times n/2 blocks:

A=[A11A12A21A22],B=[B11B12B21B22],C=AB=[C11C12C21C22].\mat{A} = \begin{bmatrix} \mat{A}_{11} & \mat{A}_{12} \\ \mat{A}_{21} & \mat{A}_{22} \end{bmatrix}, \qquad \mat{B} = \begin{bmatrix} \mat{B}_{11} & \mat{B}_{12} \\ \mat{B}_{21} & \mat{B}_{22} \end{bmatrix}, \qquad \mat{C} = \mat{A}\mat{B} = \begin{bmatrix} \mat{C}_{11} & \mat{C}_{12} \\ \mat{C}_{21} & \mat{C}_{22} \end{bmatrix}.

The block formula C11=A11B11+A12B21\mat{C}_{11} = \mat{A}_{11}\mat{B}_{11} + \mat{A}_{12}\mat{B}_{21} and its three analogues use eight block products, and T(n)=8T(n/2)+Θ(n2)T(n) = 8T(n/2) + \Theta(n^2) gives Θ(n3)\Theta(n^3) by case 1, c⋆=3c^\star = 3: no saving. In 1969 Volker Strassen proved seven suffice. Strassen’s algorithm computes

M1=(A11+A22)(B11+B22),M2=(A21+A22) B11,M3=A11(B12−B22),M4=A22(B21−B11),M5=(A11+A12) B22,M6=(A21−A11)(B11+B12),M7=(A12−A22)(B21+B22),\begin{aligned} \mat{M}_1 &= (\mat{A}_{11} + \mat{A}_{22})(\mat{B}_{11} + \mat{B}_{22}), & \mat{M}_2 &= (\mat{A}_{21} + \mat{A}_{22})\,\mat{B}_{11}, \\ \mat{M}_3 &= \mat{A}_{11}(\mat{B}_{12} - \mat{B}_{22}), & \mat{M}_4 &= \mat{A}_{22}(\mat{B}_{21} - \mat{B}_{11}), \\ \mat{M}_5 &= (\mat{A}_{11} + \mat{A}_{12})\,\mat{B}_{22}, & \mat{M}_6 &= (\mat{A}_{21} - \mat{A}_{11})(\mat{B}_{11} + \mat{B}_{12}), \\ \mat{M}_7 &= (\mat{A}_{12} - \mat{A}_{22})(\mat{B}_{21} + \mat{B}_{22}), \end{aligned}

and recombines

C11=M1+M4−M5+M7,C12=M3+M5,C21=M2+M4,C22=M1−M2+M3+M6.\mat{C}_{11} = \mat{M}_1 + \mat{M}_4 - \mat{M}_5 + \mat{M}_7, \quad \mat{C}_{12} = \mat{M}_3 + \mat{M}_5, \quad \mat{C}_{21} = \mat{M}_2 + \mat{M}_4, \quad \mat{C}_{22} = \mat{M}_1 - \mat{M}_2 + \mat{M}_3 + \mat{M}_6.

Verify by expansion. For example, C12=M3+M5=A11B12−A11B22+A11B22+A12B22=A11B12+A12B22\mat{C}_{12} = \mat{M}_3 + \mat{M}_5 = \mat{A}_{11}\mat{B}_{12} - \mat{A}_{11}\mat{B}_{22} + \mat{A}_{11}\mat{B}_{22} + \mat{A}_{12}\mat{B}_{22} = \mat{A}_{11}\mat{B}_{12} + \mat{A}_{12}\mat{B}_{22}. For C11\mat{C}_{11}, terms A11B22\mat{A}_{11}\mat{B}_{22}, A22B11\mat{A}_{22}\mat{B}_{11}, A22B22\mat{A}_{22}\mat{B}_{22}, A22B21\mat{A}_{22}\mat{B}_{21} and A12B22\mat{A}_{12}\mat{B}_{22} cancel in pairs, leaving A11B11+A12B21\mat{A}_{11}\mat{B}_{11} + \mat{A}_{12}\mat{B}_{21}. Work out the other two on paper to see the identity directly.

The identity does not use commutativity. Blocks do not commute, and every Mi\mat{M}_i respects factor order, always a block of A\mat{A} on the left and one of B\mat{B} on the right. Recursion is therefore valid over any ring. Older tricks, such as Winograd’s 1968 dot product, save multiplications but require commuting elements and cannot be applied to blocks.

The cost is T(n)=7T(n/2)+Θ(n2)T(n) = 7T(n/2) + \Theta(n^2): Θ(n2)\Theta(n^2) accounts for 18 block additions and subtractions, 10 before the products and 8 after. With c⋆=log⁡27≈2.807>2c^\star = \log_2 7 \approx 2.807 > 2, case 1 gives:

T(n)=Θ(nlog⁡27)=Θ(n2.807).T(n) = \Theta\big(n^{\log_2 7}\big) = \Theta(n^{2.807}).

For n=2kn = 2^k, recursing to size 1 gives 7k7^k scalar products versus 8k=n38^k = n^3 for the direct method. With n=64n = 64, this is 76=117 6497^6 = 117\,649 versus 643=262 14464^3 = 262\,144, a 45 %45\,\%. If the dimension is not a power of 2, pad with zeros to the next power, increasing worst-case cost by at most 77, or split blocks unevenly.

Constants, cutoff threshold and stability

The 18 additions per level matter. Counting products and additions, the classical method uses 2n3−n22n^3 - n^2 operations and one Strassen level, seven classical products of size m=n/2m = n/2 plus 18 block additions, uses 7(2m3−m2)+18m2=14m3+11m27(2m^3 - m^2) + 18m^2 = 14m^3 + 11m^2. With n=2mn = 2m the classical method costs 16m3−4m216m^3 - 4m^2, so one level helps only if 2m3>15m22m^3 > 15m^2, that is m>7.5m > 7.5 and n≥16n \ge 16. Strassen implementations therefore do not recurse to size 1: below a cutoff they use direct multiplication. A later cell measures each variant’s operation count.

The second difficulty is numerical stability. Classical multiplication has a componentwise error bound ∣C^−C∣≤γn∣A∣ ∣B∣\lvert \hat{\mat{C}} - \mat{C} \rvert \le \gamma_n \lvert \mat{A} \rvert\,\lvert \mat{B} \rvert with γn≈n u\gamma_n \approx n\,u and uu the unit roundoff. Strassen has only a normwise bound, with a worse constant growing with recursion depth (Higham, Accuracy and Stability of Numerical Algorithms, chapter on fast matrix multiplication). For matrices with widely differing row and column scales, relative errors in small entries can degrade. This remains acceptable in many applications and motivates using a couple of levels; it may not be acceptable when accurate individual entries are needed.

The matrix-multiplication exponent

Strassen opened a question: what is the best exponent? Define

ω=inf⁡{τ:dos matrices n×n se multiplican con O(nτ) operaciones}.\omega = \inf\{\tau : \text{dos matrices } n \times n \text{ se multiplican con } O(n^\tau) \text{ operaciones}\}.

This is the matrix-multiplication exponent ω\omega. We know 2≤ω<2.3711772 \le \omega < 2.371177: the lower bound follows from reading n2n^2 inputs, and the upper bound is an August 2026 result (Dupont et al., arXiv:2608.16884), not yet peer reviewed; the previous best was 2.3713392.371339. Whether ω=2\omega = 2 is unknown. For fixed-size multiplication ⟨2,2,2⟩\langle 2,2,2 \rangle, seven products are known to be optimal (Winograd, and Hopcroft and Kerr, 1971), so Strassen cannot be improved at 2×22 \times 2. For 3×33 \times 3, an algorithm with 23 products (Laderman, 1976) gives log⁡323≈2.854\log_3 23 \approx 2.854 and is worse than Strassen; the best-known lower bound is 19.

ω\omega matters beyond multiplication. Matrix inversion, determinant, rank, LU factorization and other linear-algebra problems reduce to multiplication and cost O(nω)O(n^\omega) (Bunch and Hopcroft, 1974, for inversion and LU). Thus ω\omega governs much of linear algebra’s complexity. It also appears in graphs: detecting a triangle costs O(nω)O(n^\omega) through adjacency-matrix multiplication, and all shortest paths in an undirected unweighted graph cost O(nωlog⁡n)O(n^\omega \log n) using Seidel’s algorithm.

InteractiveThe history of exponent ω\omega
2.32.42.52.62.72.81970198019902000201020202030best known upper bound on ω (lower bound is 2)not used in practiceused in practice
1990 · Coppersmith and Winograd

Laser method applied to a new tensor, with sets free of three-term arithmetic progressions (Salem and Spencer, Behrend) to separate blocks. It remained the record for about twenty years.

Constants. Astronomical hidden constant: no practical implementation is known.

Milestone
1990
What the bound buys
10 000
Upper bound on ω\omega2.3755
Year1990
Asymptotic factor n3−ωn^{3-\omega} versus n3n^3314.8
The factor is asymptotic: hidden constants make it irrelevant at any real size.
The best-known upper bound on ω\omega since Strassen. Select each milestone or use the slider to see the technical idea and hidden constant. Zooming from 2010 shows recent improvements between the third and sixth decimal places. The size slider shows the asymptotic advantage n3−ωn^{3-\omega} over the classical method, in the thousands at n=106n = 10^6. Why are none of the algorithms lower in the list used?

Modern treatment uses multilinear algebra. Matrix multiplication is a tensor ⟨n,n,n⟩\langle n,n,n \rangle and ω\omega measures how its tensor rank grows with nn. A small-size algorithm with RR products yields ω≤log⁡nR\omega \le \log_n R recursively, just as Strassen does with n=2n = 2 and R=7R = 7. Improvements since 1981, including Schönhage and Coppersmith-Winograd using Strassen’s laser method, analyze powers of a carefully chosen tensor. These are galactic algorithms: better exponents come with constants so large they are impractical for any input fitting on a real machine. Practice uses highly optimized classical matrix products with memory and cache tuning, or at most one or two Strassen levels. Two qualifications: the best-known lower bound for multiplication using bounded-coefficient arithmetic circuits is Ω(n2log⁡n)\Omega(n^2 \log n) (Raz, 2002), and reinforcement-learning searches such as AlphaTensor (DeepMind, 2022) have found fewer-product algorithms for particular small sizes, some valid only modulo 2, including one for 4×44 \times 4 with 47 products versus 49=7249 = 7^2 for two Strassen levels. The 2026 bound above optimized its analysis with AlphaEvolve. The final lesson discusses such AI-assisted discoveries.

Geometry: closest pair of points

Given nn points in the plane, which pair has the smallest Euclidean distance? Brute force compares (n2)\binom{n}{2} pairs. The divide-and-conquer closest-pair algorithm (Shamos and Hoey, 1975) solves this in O(nlog⁡n)O(n \log n):

  1. Sort points by xx once and by yy once.
  2. Divide at median xx into left half LL and right half RR, with dividing line x=xmx = x_m.
  3. Solve recursively: δL\delta_L and δR\delta_R are the halves’ minimum distances. Let δ=min⁡(δL,δR)\delta = \min(\delta_L, \delta_R).
  4. Combine: the best pair is either within a half, at distance δ\delta, or crosses the dividing line. To cross with distance below δ\delta, both points must lie within δ\delta of the line, in the strip {p:∣px−xm∣<δ}\{p : \lvert p_x - x_m \rvert < \delta\}. Scan strip points in increasing yy order, comparing each only with subsequent points whose yy coordinate differs by less than δ\delta.

Each strip point is compared with only a constant number of subsequent points. Although the strip might contain every point, packing limits the relevant neighbors:

Proof

Rectangle 2δ×δ2\delta \times \delta is the union of two squares of side δ\delta, one on each side of the dividing line. Points of LL in the left square are separated by at least δL≥δ\delta_L \ge \delta. Divide the square into four closed squares of side δ/2\delta/2 and diagonal δ/2<δ\delta/\sqrt{2} < \delta. Two points in one small square would be closer than δ\delta. By the pigeonhole principle, the left square has at most 4 points of LL. The same holds on the right for RR, minimum distance δR≥δ\delta_R \ge \delta. Points of LL lie left of xmx_m or on the line, and RR lie right or on it, so every rectangle point is counted in its half’s square. Total ≤4+4=8\le 4 + 4 = 8. ■\qquad\blacksquare

∎
InteractiveThe closest-pair strip
medianstrip of width 2δ
  • left half and its best pair
  • right half and its best pair
  • selected point and its rectangle
Strip point
1 of 5
δL\delta_L (left half)1.53
δR\delta_R (right half)1.84
δ=min⁡(δL,δR)\delta = \min(\delta_L, \delta_R)1.53
Points in strip5 of 16
Candidates for selected point2 (maximum 7)
Strip comparisons4
Brute force120
Closest pair0.82
The best pair crosses the median: without the strip it would have been missed.
Drag the points. The dashed line is the median; blue and orange show the two halves and their closest pairs as thick segments; the shaded strip has width 2δ2\delta. Select a strip point using the slider: it is compared only with enclosed points in the δ×2δ\delta \times 2\delta rectangle above. Compare strip comparisons with the (n2)\binom{n}{2} brute-force pairs. Switch to «Empaquetamiento» and try placing a ninth point without two in the same half coming within δ\delta.

Combination costs O(n)O(n), with at most 7 comparisons per strip point, giving recurrence T(n)=2T(n/2)+O(n)T(n) = 2T(n/2) + O(n) and O(nlog⁡n)O(n \log n) by case 2. A frequently missed condition matters: scanning the strip ordered by yy requires points sorted by yy at every level. Sorting from scratch in each call makes combination cost O(nlog⁡n)O(n \log n) and yields recurrence T(n)=2T(n/2)+O(nlog⁡n)T(n) = 2T(n/2) + O(n\log n), of order nlog⁡2nn\log^2 n. Instead merge by yy when recursion returns, as mergesort does, so each call returns its list sorted by yy without extra asymptotic cost. Check this in the implementation below.

O(nlog⁡n)O(n \log n) is optimal in the algebraic decision-tree model by reduction from element uniqueness, requiring Ω(nlog⁡n)\Omega(n \log n). Randomization and a hash table over a grid give expected linear cost (Rabin, 1976; Khuller and Matias, 1995), outside the comparison model.

Voronoi and Delaunay

Closest pair asks which points are near one another. The Voronoi diagram and its dual, the Delaunay triangulation, answer these proximity questions together.

Delaunay contains the required structures as subgraphs:

Proof

The counts follow from Euler’s planar-graph formula, V−E+F=2V - E + F = 2 with FF including the outer face, and the fact that each interior face has 3 edges while the outer face has hh: 3t+h=2E3t + h = 2E, together with n−E+(t+1)=2n - E + (t + 1) = 2. Solving gives t=2n−2−ht = 2n - 2 - h and E=3n−3−hE = 3n - 3 - h.

For (a), let qq be the nearest neighbor of pp. The disk with diameter pqpq contains no other site rr inside. Otherwise angle prq^\widehat{prq} would exceed 90∘90^\circ and ∥p−r∥<∥p−q∥\lVert p - r \rVert < \lVert p - q \rVert, contradicting the choice of qq. An empty disk through pp and qq has two sites on its boundary and none inside, characterizing Delaunay edges: pq∈DT(S)pq \in \mathrm{DT}(S).

For (b), let pqpq be an edge of a minimum spanning tree. In the same disk of diameter pqpq, an interior site rr would make both ∥p−r∥\lVert p - r \rVert and ∥r−q∥\lVert r - q \rVert shorter than ∥p−q∥\lVert p - q \rVert. Replacing pqpq by prpr or rqrq would produce a lighter tree, contradicting minimality. The disk is empty and pq∈DT(S)pq \in \mathrm{DT}(S). ■\qquad\blacksquare

∎

The algorithmic consequence is strong. A Euclidean minimum spanning tree of nn points seems to require considering (n2)\binom{n}{2} pairs, but it suffices to construct DT(S)\mathrm{DT}(S) and run Kruskal on its O(n)O(n) edges, total cost O(nlog⁡n)O(n \log n). Delaunay triangulation can be built in O(nlog⁡n)O(n \log n) by divide and conquer (Guibas and Stolfi, 1985: triangulate each half and stitch along the common lower tangent in linear time, giving T(n)=2T(n/2)+O(n)T(n) = 2T(n/2) + O(n)), by sweeping (Fortune, 1987), or randomized incremental construction. The figure uses simpler Bowyer-Watson, O(n2)O(n^2) worst case, suitable for few points. Delaunay also maximizes the smallest angle among triangulations of SS, a reason for its use in finite-element meshes.

InteractiveDelaunay, Voronoi and what they contain
  • triangulation edges
  • Voronoi cells
  • nearest neighbor
  • minimum spanning tree
Triangulation
Layers
Points nn / hull hh12 / 7
Triangles (expected 2n−2−h2n - 2 - h)15 (15)
Edges (expected 3n−3−h3n - 3 - h)26 (26)
Triangles with nonempty circumcircle0
Nearest neighbor in triangulation12 of 12
MST edges in triangulation11 of 11
The 12 nearest neighbors and 11 MST edges are always in Delaunay. Circle under pointer: 0 points inside.
Drag points to recompute the triangulation and diagram. Hover over a triangle to see its circumcircle: in Delaunay it is empty and its center is a Voronoi vertex. Enable «Vecino más próximo» and «Árbol generador mínimo» and check that all their edges belong to the triangulation. Switch to greedy triangulation, adding noncrossing edges in length order: it is valid, but the initial points yield two circles containing points, shown red and counted in the readout. Both triangulations satisfy Euler's counts.

Inversion counting and Kendall distance

An inversion of sequence a1,…,ana_1, \dots, a_n is a pair i<ji < j with ai>aja_i > a_j. A sorted list has 0 inversions and a reversed list (n2)\binom{n}{2}. Inversion count measures disorder and equals the Kendall distance between two rankings: the number of element pairs on which they disagree. Write one ranking in the other’s order and count inversions of the resulting permutation. Brute-force counting costs Θ(n2)\Theta(n^2), while mergesort counts as it goes in Θ(nlog⁡n)\Theta(n \log n):

  • When merging sorted halves LL and RR, whenever an element of RR is taken before one of LL, it forms an inversion with every untaken element of LL.
  • Total inversions comprise those in LL, those in RR, and crossings between halves. Count the latter during merge at constant cost per element, giving T(n)=2T(n/2)+Θ(n)T(n) = 2T(n/2) + \Theta(n).

The relationship with rank correlation is an identity. If dd is Kendall distance between tie-free rankings of nn elements, Kendall coefficient τ\tau is τ=1−2d/(n2)\tau = 1 - 2d/\binom{n}{2}, ranging from −1-1 for opposite rankings to 11 for identical ones. This efficiently evaluates a recommender or search engine against a reference ordering.

Implementation from scratch

First examine recurrence behavior. Simulate T(n)T(n) exactly for n=2kn = 2^k and divide by the theorem’s prediction. If the predicted order is correct, the ratio stabilizes at a constant; otherwise it drifts.

[ ]Simulate recurrences and compare with the master theoremBrowser
import math
from functools import lru_cache

def simular(a, b, f):
    """T(n) = a T(n/b) + f(n) con T(1) = 1, definida sobre n = b**k."""
    @lru_cache(maxsize=None)
    def T(n):
        return 1.0 if n == 1 else a * T(n // b) + f(n)
    return T

casos = [
    ("4T(n/2) + n^2     (caso 2)", 4, 2, lambda n: n**2,            lambda n: n**2 * math.log2(n)),
    ("7T(n/2) + n^2     (caso 1)", 7, 2, lambda n: n**2,            lambda n: n**math.log2(7)),
    ("3T(n/2) + n       (caso 1)", 3, 2, lambda n: n,               lambda n: n**math.log2(3)),
    ("2T(n/2) + n^2     (caso 3)", 2, 2, lambda n: n**2,            lambda n: n**2),
    ("2T(n/2) + n log n (caso 2, k=1)", 2, 2, lambda n: n * math.log2(n), lambda n: n * math.log2(n)**2),
    ("2T(n/2) + n log n contra n log n (predicción errónea)", 2, 2, lambda n: n * math.log2(n), lambda n: n * math.log2(n)),
]
for nombre, a, b, f, pred in casos:
    T = simular(a, b, f)
    razones = [T(2**k) / pred(2**k) for k in (8, 12, 16, 20)]
    print(f"{nombre:56s}", "  ".join(f"{r:8.3f}" for r in razones))

The first five rows stabilize at constants, including nlog⁡nn\log n in the fifth toward 1/21/2, slowly because T(n)=12nlog⁡2n+Θ(nlog⁡n)T(n) = \tfrac{1}{2}n\log^2 n + \Theta(n\log n). The last uses nlog⁡nn\log n for 2T(n/2)+nlog⁡n2T(n/2) + n\log n and grows without bound: this is the earlier missing-logarithm error. Next compute the Akra-Bazzi exponent and simulate median-of-medians with floors:

[ ]Akra-Bazzi: exponent p and the median-of-medians constantBrowser
import math
from functools import lru_cache

def exponente_p(a_b, tol=1e-12):
    """Raíz de sum(a_i * b_i^p) = 1 por bisección; la función es decreciente en p."""
    suma = lambda p: sum(a * b**p for a, b in a_b)
    lo, hi = -10.0, 10.0
    while hi - lo > tol:
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if suma(mid) > 1 else (lo, mid)
    return (lo + hi) / 2

for nombre, ab in [
    ("T(n/2) x 2 (mergesort)", [(2, 1/2)]),
    ("T(n/5) + T(7n/10)",       [(1, 1/5), (1, 7/10)]),
    ("T(n/3) + T(2n/3)",        [(1, 1/3), (1, 2/3)]),
    ("T(n/4) + T(n/2)",         [(1, 1/4), (1, 1/2)]),
]:
    print(f"{nombre:26s} p = {exponente_p(ab):.4f}")

@lru_cache(maxsize=None)
def M(n):                                   # mediana de medianas, con suelos
    return 1 if n < 5 else M(n // 5) + M(7 * n // 10) + n

@lru_cache(maxsize=None)
def D(n):                                   # T(n/3) + T(2n/3) + n
    return 1 if n < 3 else D(n // 3) + D(2 * n // 3) + n

print("\nM(n) / n, tiende a 10:", [round(M(n) / n, 3) for n in (10**3, 10**5, 10**7, 10**9)])
print("D(n) / (n log2 n):    ", [round(D(n) / (n * math.log2(n)), 3) for n in (10**3, 10**5, 10**7, 10**9)])

Now implement Karatsuba on digit lists, least significant first, with a cutoff below which schoolbook multiplication is used. Instead of browser timings, which are noisy, count elementary digit products and additions independently of the machine.

[ ]Karatsuba with digit lists and a cutoffBrowser
import random

ops = 0     # operaciones elementales sobre cifras: un producto o una suma

def a_lista(x):
    return [int(c) for c in reversed(str(x))] if x else [0]

def a_entero(d):
    return int("".join(map(str, reversed(d))))

def recortar(d):
    while len(d) > 1 and d[-1] == 0:
        d.pop()
    return d

def sumar(a, b):
    global ops
    r, acarreo = [], 0
    for i in range(max(len(a), len(b))):
        s = (a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0) + acarreo
        r.append(s % 10); acarreo = s // 10
        ops += 1
    if acarreo:
        r.append(acarreo)
    return r

def restar(a, b):
    """a - b, con a >= b."""
    global ops
    r, prestamo = [], 0
    for i in range(len(a)):
        s = a[i] - (b[i] if i < len(b) else 0) - prestamo
        prestamo = 1 if s < 0 else 0
        r.append(s + 10 * prestamo)
        ops += 1
    return recortar(r)

def escolar(a, b):
    global ops
    r = [0] * (len(a) + len(b))
    for i, x in enumerate(a):
        acarreo = 0
        for j, y in enumerate(b):
            t = r[i + j] + x * y + acarreo
            r[i + j] = t % 10; acarreo = t // 10
            ops += 2                                   # un producto y una suma
        r[i + len(b)] += acarreo
    return recortar(r)

def desplazar(a, k):
    return [0] * k + a if a != [0] else [0]

def karatsuba(a, b, umbral=1):
    n = max(len(a), len(b))
    if n <= umbral:
        return escolar(a, b)
    h = (n + 1) // 2
    a = a + [0] * (n - len(a)); b = b + [0] * (n - len(b))
    a0, a1 = recortar(a[:h]), recortar(a[h:] or [0])
    b0, b1 = recortar(b[:h]), recortar(b[h:] or [0])
    p1 = karatsuba(a1, b1, umbral)
    p2 = karatsuba(a0, b0, umbral)
    p3 = karatsuba(sumar(a1, a0), sumar(b1, b0), umbral)       # (x1 + x0)(y1 + y0)
    cruzado = restar(restar(p3, p1), p2)                       # x1 y0 + x0 y1
    return recortar(sumar(sumar(desplazar(p1, 2 * h), desplazar(cruzado, h)), p2))

random.seed(1)
for n in (8, 64, 257):                                         # corrección frente a Python
    x, y = random.randrange(10**(n - 1), 10**n), random.randrange(10**(n - 1), 10**n)
    assert a_entero(karatsuba(a_lista(x), a_lista(y), 4)) == x * y
print("resultados correctos frente a x * y\n")

print(f"{'n':>5} {'escolar':>9} {'umbral 1':>9} {'umbral 8':>9} {'umbral 16':>9}")
for n in (16, 64, 256, 512):
    x, y = random.randrange(10**(n - 1), 10**n), random.randrange(10**(n - 1), 10**n)
    A, B = a_lista(x), a_lista(y)
    ops = 0; escolar(A, B); base = ops
    fila = []
    for u in (1, 8, 16):
        ops = 0; karatsuba(A, B, u); fila.append(ops)
    print(f"{n:>5} {base:>9} " + " ".join(f"{v:>9}" for v in fila))

Two observations. Recursing to one digit, cutoff 1, is worse than schoolbook multiplication until several hundred digits and only matches it around n=512n = 512. With a cutoff of 8 to 16, Karatsuba wins at 64 digits and uses roughly one third as many operations at 512. Asymptotic n1.585n^{1.585} becomes visible only when size greatly exceeds the constant. The curve is flat near its optimum: at 512 digits, cutoffs 8 and 16 differ by 5 %5\,\%.

Now Strassen with NumPy. Blocks are views without copies, and the base case uses A @ B.

[ ]Strassen with a cutoff, operation counts and numerical errorBrowser
import numpy as np

def strassen(A, B, umbral=64):
    """A @ B para matrices cuadradas de lado potencia de 2; por debajo del umbral, producto directo."""
    n = A.shape[0]
    if n <= umbral:
        return A @ B
    m = n // 2
    A11, A12, A21, A22 = A[:m, :m], A[:m, m:], A[m:, :m], A[m:, m:]
    B11, B12, B21, B22 = B[:m, :m], B[:m, m:], B[m:, :m], B[m:, m:]
    M1 = strassen(A11 + A22, B11 + B22, umbral)
    M2 = strassen(A21 + A22, B11, umbral)
    M3 = strassen(A11, B12 - B22, umbral)
    M4 = strassen(A22, B21 - B11, umbral)
    M5 = strassen(A11 + A12, B22, umbral)
    M6 = strassen(A21 - A11, B11 + B12, umbral)
    M7 = strassen(A12 - A22, B21 + B22, umbral)
    C = np.empty((n, n), dtype=np.result_type(A, B))
    C[:m, :m] = M1 + M4 - M5 + M7
    C[:m, m:] = M3 + M5
    C[m:, :m] = M2 + M4
    C[m:, m:] = M1 - M2 + M3 + M6
    return C

def productos(n, umbral):
    return n**3 if n <= umbral else 7 * productos(n // 2, umbral)

def operaciones(n, umbral):
    """(productos, sumas) con el método directo por debajo del umbral."""
    if n <= umbral:
        return n**3, n**2 * (n - 1)
    mu, su = operaciones(n // 2, umbral)
    return 7 * mu, 7 * su + 18 * (n // 2)**2

rng = np.random.default_rng(0)
A, B = rng.standard_normal((64, 64)), rng.standard_normal((64, 64))
print("n = 64: productos escalares y error máximo frente a A @ B")
for u in (64, 32, 16, 8, 4):
    print(f"  umbral {u:>2}: {productos(64, u):>7} productos   error {np.abs(strassen(A, B, u) - A @ B).max():.1e}")
print(f"  (n^3 = {64**3}; hasta tamaño 1 serían 7^6 = {productos(64, 1)})")

print("\nproductos + sumas con n = 64:")
for u in (64, 32, 16, 8, 4, 2, 1):
    mu, su = operaciones(64, u)
    print(f"  umbral {u:>2}: {mu + su:>7}")

print("\nn = 128 en float32: error relativo máximo frente a float64, según los niveles de recursión")
A, B = rng.standard_normal((128, 128)), rng.standard_normal((128, 128))
ref = A @ B
A32, B32 = A.astype(np.float32), B.astype(np.float32)
err = lambda C: np.abs(C.astype(float) - ref).max() / np.abs(ref).max()
print(f"  clásico (0 niveles): {err(A32 @ B32):.1e}")
for niveles, u in enumerate((64, 32, 16, 8, 4), start=1):
    print(f"  {niveles} niveles (umbral {u:>2}):   {err(strassen(A32, B32, u)):.1e}")

The operation count is minimized at an intermediate cutoff around 8: 436 416436\,416 operations versus 520 192520\,192 for direct multiplication, 16 %16\,\% fewer. That cutoff saves 33 %33\,\% of products, 175 616175\,616 versus 262 144262\,144. Additions consume much of the gain; excessive recursion, such as cutoff 1 (798 967798\,967), makes the method much worse. In float32, error grows with recursion depth, from 3.7×10−73.7\times 10^{-7} for classical multiplication to 5.4×10−65.4\times 10^{-6} at five levels, about fifteen times more. This loss and NumPy’s highly tuned direct BLAS explain why numpy.matmul does not use Strassen.

Now compute closest pair in O(nlog⁡n)O(n\log n), merging by yy instead of resorting, and count inversions. Validate both against brute force.

[ ]Closest pair and inversions, validated against brute forceBrowser
import math, random

def mas_cercano(puntos):
    """Distancia mínima entre puntos del plano en O(n log n): se ordena por x una sola vez."""
    def rec(px):
        """px ordenado por x. Devuelve (delta, puntos ordenados por y)."""
        n = len(px)
        if n <= 3:
            d = min((math.dist(px[i], px[j]) for i in range(n) for j in range(i + 1, n)), default=math.inf)
            return d, sorted(px, key=lambda p: p[1])
        m = n // 2
        xm = px[m][0]
        dl, yl = rec(px[:m])
        dr, yr = rec(px[m:])
        d = min(dl, dr)
        py, i, j = [], 0, 0                          # mezcla por y, como en mergesort
        while i < len(yl) and j < len(yr):
            if yl[i][1] <= yr[j][1]:
                py.append(yl[i]); i += 1
            else:
                py.append(yr[j]); j += 1
        py += yl[i:] + yr[j:]
        franja = [p for p in py if abs(p[0] - xm) < d]
        for a in range(len(franja)):
            b = a + 1
            while b < len(franja) and franja[b][1] - franja[a][1] < d:   # a lo sumo 7 candidatos
                d = min(d, math.dist(franja[a], franja[b]))
                b += 1
        return d, py
    return rec(sorted(puntos))[0]

def fuerza_bruta(puntos):
    return min(math.dist(puntos[i], puntos[j]) for i in range(len(puntos)) for j in range(i + 1, len(puntos)))

def inversiones(a):
    """(lista ordenada, número de inversiones) por mezcla."""
    if len(a) <= 1:
        return a, 0
    m = len(a) // 2
    izq, ci = inversiones(a[:m])
    der, cd = inversiones(a[m:])
    mezcla, cruzan, i, j = [], 0, 0, 0
    while i < len(izq) and j < len(der):
        if izq[i] <= der[j]:
            mezcla.append(izq[i]); i += 1
        else:
            mezcla.append(der[j]); j += 1
            cruzan += len(izq) - i                   # der[j] es menor que todos los izq restantes
    mezcla += izq[i:] + der[j:]
    return mezcla, ci + cd + cruzan

random.seed(3)
for n in (2, 5, 30, 200):
    P = [(random.random(), random.random()) for _ in range(n)]
    assert abs(mas_cercano(P) - fuerza_bruta(P)) < 1e-12
assert mas_cercano([(i, j) for i in range(6) for j in range(6)]) == 1.0      # rejilla: muchas x repetidas
for n in (0, 1, 7, 100):
    a = [random.randrange(50) for _ in range(n)]
    assert inversiones(a)[1] == sum(a[i] > a[j] for i in range(n) for j in range(i + 1, n))
print("par más cercano e inversiones coinciden con la fuerza bruta")
print("inversiones de [2, 4, 1, 3, 5]:", inversiones([2, 4, 1, 3, 5])[1], " de la invertida de 1000:", inversiones(list(range(1000, 0, -1)))[1], " = C(1000,2) =", 1000 * 999 // 2)

Library version

SciPy provides scipy.spatial.cKDTree for nearest neighbors, scipy.spatial.Delaunay over Qhull, and scipy.stats.kendalltau. Use them to verify the Voronoi and Delaunay section: Euler counts, the empty-circle property, nearest-neighbor and minimum-spanning-tree edges inside Delaunay, and computing the MST using only Delaunay edges.

[ ]Delaunay, nearest neighbor, MST and Kendall with SciPyBrowser
import numpy as np
from scipy.spatial import Delaunay, cKDTree
from scipy.spatial.distance import cdist
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
from scipy.stats import kendalltau

rng = np.random.default_rng(5)
P = rng.random((60, 2))
tri = Delaunay(P)
h = len(np.unique(tri.convex_hull))
print(f"n = {len(P)}, envolvente h = {h}, triángulos = {len(tri.simplices)} (2n-2-h = {2 * len(P) - 2 - h})")

E = set()
for a, b, c in tri.simplices:
    E |= {tuple(sorted(p)) for p in ((a, b), (b, c), (a, c))}
print(f"aristas = {len(E)} (3n-3-h = {3 * len(P) - 3 - h})")

def circulo(a, b, c):
    M = 2 * np.array([b - a, c - a])
    centro = np.linalg.solve(M, np.array([b @ b - a @ a, c @ c - a @ a]))
    return centro, np.linalg.norm(centro - a)

margen = np.inf
for s in tri.simplices:
    centro, r = circulo(*P[s])
    d = np.linalg.norm(P - centro, axis=1)
    d[s] = np.inf
    margen = min(margen, (d - r).min())
print("distancia mínima de un punto ajeno al borde de un círculo circunscrito:", round(margen, 6), "(positiva: todos vacíos)")

dd, vecino = cKDTree(P).query(P, k=2)
print("vecinos más próximos en Delaunay:", all(tuple(sorted((i, j))) in E for i, j in enumerate(vecino[:, 1])))
print(f"par más cercano: desde cero {mas_cercano([tuple(p) for p in P.tolist()]):.12f}   con cKDTree {dd[:, 1].min():.12f}")

D = cdist(P, P)
mst = minimum_spanning_tree(D).tocoo()
aristas_mst = {tuple(sorted(e)) for e in zip(mst.row, mst.col)}
print("aristas del MST:", len(aristas_mst), " todas en Delaunay:", aristas_mst <= E)

i, j = map(list, zip(*E))
solo_delaunay = coo_matrix((D[i, j], (i, j)), shape=D.shape)
print(f"peso del MST con todos los pares: {mst.sum():.6f}   con solo las {len(E)} aristas de Delaunay: {minimum_spanning_tree(solo_delaunay).sum():.6f}")

# Distancia de Kendall = inversiones de un ranking escrito en el orden del otro
r1 = rng.permutation(12)
r2 = rng.permutation(12)
orden = np.argsort(r1)                                  # elementos ordenados según el primer ranking
d_k = sum(r2[orden][a] > r2[orden][b] for a in range(12) for b in range(a + 1, 12))
tau = kendalltau(r1, r2)[0]
print(f"distancia de Kendall = {d_k},  tau de scipy = {tau:.4f},  1 - 2d/C(12,2) = {1 - 2 * d_k / 66:.4f}")

Common mistakes

Exercises

QuizThree recurrences
What are the growth orders of these three recurrences, in order? T1(n)=4T1(n/2)+n2T_1(n) = 4T_1(n/2) + n^2, T2(n)=7T2(n/2)+n2T_2(n) = 7T_2(n/2) + n^2, T3(n)=2T3(n/2)+nlog⁡nT_3(n) = 2T_3(n/2) + n\log n.
QuizWhen the master theorem is insufficient
Which recurrences cannot be solved with the master theorem, including its extended case 2?

More than one answer may be correct.

NumericThe Akra-Bazzi exponent
For T(n)=T(n/4)+T(n/2)+nT(n) = T(n/4) + T(n/2) + n, calculate the Akra-Bazzi exponent pp, the solution to (1/4)p+(1/2)p=1(1/4)^p + (1/2)^p = 1.
NumericSingle-digit products
Multiply two 6464-digit numbers with Karatsuba, recursing to one digit. How many single-digit products are made? Schoolbook multiplication uses 642=409664^2 = 4096.
NumericThe exact value of T(1024)
Let T(1)=1T(1) = 1 and T(n)=3T(n/2)+nT(n) = 3T(n/2) + n for n=2kn = 2^k. Compute T(1024)T(1024).
NumericStrassen products for $n = 64$
How many scalar multiplications does Strassen make on two 64×6464 \times 64 matrices when recursively applied to size 1?
QuizThe cross term
In Karatsuba, given P1=x1y1P_1 = x_1y_1 and P2=x0y0P_2 = x_0y_0, which additional product yields x1y0+x0y1x_1y_0 + x_0y_1 by subtraction?
ProofProve case 2
Prove: If T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n) with f(n)=Θ(nc⋆)f(n) = \Theta(n^{c^\star}), c⋆=log⁡bac^\star = \log_b a and n=bLn = b^L, then T(n)=Θ(nc⋆log⁡n)T(n) = \Theta(n^{c^\star}\log n).
0
Expand the recurrence by level: T(n)=∑j=0L−1ajf(n/bj)+aLT(1)T(n) = \sum_{j=0}^{L-1} a^j f(n/b^j) + a^L T(1).

Step 1 of 4. What is the level-jj term?

ProofEach strip point is compared with a constant number of points
Prove: For closest pair, let δ=min⁡(δL,δR)\delta = \min(\delta_L, \delta_R) and let pp be a strip point. At most 8 strip points, including pp, have vertical coordinate in [py,py+δ)[p_y, p_y + \delta).
0
All these points lie in rectangle [xm−δ,xm+δ]×[py,py+δ][x_m - \delta, x_m + \delta] \times [p_y, p_y + \delta], the union of two side-δ\delta squares separated by the dividing line.

Step 1 of 3. What is known about distances between points in each square?

CodeCount inversions in O(n log n)
Implement contar_inversiones(a) to return the number of pairs i < j with a[i] > a[j], counting strict inversions and excluding ties, in O(nlog⁡n)O(n\log n) time. Do not modify the input list. Tests compare the result with brute force and check that element comparisons grow as nlog⁡nn\log n; for n=2048n = 2048, a quadratic solution exceeds two million.
def contar_inversiones(a):
  """Número de pares i < j con a[i] > a[j], en O(n log n)."""
  # tu código: ordena por mezcla y cuenta, al mezclar, los elementos de la izquierda
  # que quedan sin tomar cada vez que se toma uno de la derecha
  return 0
Shift+Enter to run

Summary

Key idea
Dividing a problem, solving subproblems and combining them yields the sum of a recursion tree. Critical exponent log⁡ba\log_b a decides whether work lies in the leaves, all levels or the root. Major improvements in this lesson, Karatsuba and Strassen, reduce aa by replacing products with additions.
  • Solve T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n) by comparing f(n)f(n) with nlog⁡ban^{\log_b a}: leaves dominate in case 1, Θ(nlog⁡ba)\Theta(n^{\log_b a}); all levels weigh equally in case 2 with an extra log⁡n\log n factor; or the root dominates in case 3, Θ(f)\Theta(f), subject to regularity. The proof sums a geometric recursion tree.
  • The master theorem misses gaps such as nc⋆/log⁡nn^{c^\star}/\log n, failed regularity and unequal subproblems. Use level sums, substitution or Akra-Bazzi, ∑aibip=1\sum a_ib_i^p = 1 and T=Θ(xp(1+∫1xg(u)u−p−1du))T = \Theta\big(x^p(1 + \int_1^x g(u)u^{-p-1}\mathrm{d}u)\big).
  • Karatsuba, 3T(n/2)+Θ(n)3T(n/2) + \Theta(n), gives Θ(n1.585)\Theta(n^{1.585}). Strassen, 7T(n/2)+Θ(n2)7T(n/2) + \Theta(n^2), gives Θ(n2.807)\Theta(n^{2.807}) and works over noncommutative rings. Both need a cutoff; Strassen has worse numerical stability.
  • ω\omega, the matrix-multiplication exponent, satisfies 2≤ω<2.3711772 \le \omega < 2.371177, a recent bound still awaiting peer review. It governs inversion, determinant and many graph problems. Algorithms pushing it toward 2 are galactic.
  • Closest pair uses a strip of width 2δ2\delta and packing, at most 8 points in rectangle 2δ×δ2\delta \times \delta, for linear combination and Θ(nlog⁡n)\Theta(n\log n) if merging by yy instead of resorting.
  • Delaunay and Voronoi: Delaunay contains nearest-neighbor and Euclidean MST edges, so that MST can be found in O(nlog⁡n)O(n\log n).
  • Inversions: mergesort counts them in Θ(nlog⁡n)\Theta(n\log n), giving Kendall distance between rankings.