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 -digit numbers by the schoolbook method takes 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 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 -digit numbers takes only three products of -digit numbers rather than four. Applied recursively, the cost falls to .
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 .
- 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 of elementary sorts to , is the textbook example. It divides the list in two (), recursively sorts both halves and merges them in linear time (), giving . Binary search, with , and , 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.
| Algorithm | ||||
|---|---|---|---|---|
| Binary search | 1 | 2 | ||
| Mergesort, inversion counting | 2 | 2 | ||
| Closest pair of points | 2 | 2 | ||
| Schoolbook block multiplication | 4 | 2 | ||
| Karatsuba | 3 | 2 | ||
| Block matrix multiplication, 8 products | 8 | 2 | ||
| Strassen | 7 | 2 |
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 . The inductive step assumes the algorithm solves all smaller instances than correctly, including the 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 ; 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 , the root performs work and creates children, each a subproblem of size . Level has nodes, each with subproblem size and local cost . The tree has internal levels and leaves, each with constant cost. Summing by level,
The number is the critical exponent throughout this lesson: it controls the growth of the leaf count. Compare three rates. Node count is multiplied by at each level; each subproblem’s size is divided by , so if , each node’s cost is divided by . Total level cost is multiplied by when descending a level. This determines which work dominates:
- If , or , cost grows downward and the last level dominates: the leaves.
- If , or , all levels cost the same and total cost is one level’s cost times the number of levels.
- If , or , cost decreases downward and the root dominates.
The figure makes the pattern visible. In mergesort and closest pair, all levels cost the same, , giving times the number of levels, . In Karatsuba, , and , bars grow downward and leaves outweigh all other levels: . When the root dominates, for example , and , 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 is the usual form in recent editions of Cormen, Leiserson, Rivest and Stein; earlier editions gave only . Second, the assumptions in cases 1 and 3 are polynomial: must be below or above by a factor ; a logarithmic factor is insufficient. Third, the theorem has gaps, discussed after the proof.
Proof
Work with . The tree gives exactly
Study the sum in each case, writing as follows from .
Case 1. By hypothesis, there is a constant with for large . Then because . This geometric series has ratio :
using . Small-size terms, for which is not bounded this way, sum to at most a constant times . Including leaves gives .
Case 2. With , the level term is because . With the logarithm is , and
since lies between and for . Because , we obtain , dominating leaves . For , this is the sum of copies of .
Case 3. Applying regularity times gives while sizes are large. Levels below a constant size contribute , as in case 1. Thus . Also from term , so . Leaves contribute because and do not change the result.
∎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 is not a power of , bound between consecutive powers using the monotonicity of 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.
- falls between cases without polynomial separation. If (), it is not and does not satisfy case 2 with . Summing levels gives , or . If , the sum converges and .
- Regularity fails. Case 3’s condition does not follow from for arbitrary functions. With (), define on powers of 2 by if is even and if is odd. Thus oscillates between and . holds, but for odd , exceeds once : no works. Case 3’s conclusion is false: for odd , is not . If with , regularity follows automatically with , so it rarely needs separate checking in practice.
- Unequal subproblem sizes, such as , sizes not exact fractions of , or a number of subproblems depending on .
The last case has a more general tool.
Akra-Bazzi: unequal subproblems
The terms absorb floors and ceilings: is plus bounded error. This justifies moving from powers of to general . Exponent is unique because is strictly decreasing: each decreases with since .
The master theorem is the special case , , with term of multiplicity . Equation gives . For , the integral is if and if . Thus:
- if , the integral converges to a constant and , case 1;
- if , the integral is and , case 2;
- if , the integral has order and , 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 . 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 , hypothesis does not close the induction, but does. Case has because , so . The tree is unbalanced but levels weigh equally until the shorter branch ends, as in case 2.
Karatsuba: three products instead of four
Let and be -digit integers, with even , and . Split each in half: , , with of digits. Then
These are four half-size products, and recurrence , where accounts for additions and shifts, gives by case 1: no improvement. Karatsuba’s algorithm observes that the middle term need not be computed as two products. Compute three:
and obtain the cross term by subtraction: . This is Gauss’s trick for multiplying complex numbers with three real products instead of four. Now , with : case 1,
For digits, recursive calls form a ternary tree of depth with single-digit products at the leaves, versus for schoolbook multiplication. With 64 digits there are products versus ; with 1024 digits, versus .
Sum can have digits due to carry, so recursive calls are no longer exactly half-size. Akra-Bazzi absorbs this through terms without changing the order. The figure uses a carry-free variant: gives with operands still at most digits long, at the cost of tracking the sign.
From integers to polynomials and the FFT
The argument does not require to be a power of 10. If 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 pieces and evaluates polynomials at points, obtaining the product with products of size , giving : with , . 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 operations and integer multiplication in (Schönhage and Strassen, 1971). Harvey and van der Hoeven reached 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 matrices using the definition of matrix multiplication requires products and additions. Split the matrices into blocks:
The block formula and its three analogues use eight block products, and gives by case 1, : no saving. In 1969 Volker Strassen proved seven suffice. Strassen’s algorithm computes
and recombines
Verify by expansion. For example, . For , terms , , , and cancel in pairs, leaving . Work out the other two on paper to see the identity directly.
The identity does not use commutativity. Blocks do not commute, and every respects factor order, always a block of on the left and one of 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 : accounts for 18 block additions and subtractions, 10 before the products and 8 after. With , case 1 gives:
For , recursing to size 1 gives scalar products versus for the direct method. With , this is versus , a . If the dimension is not a power of 2, pad with zeros to the next power, increasing worst-case cost by at most , or split blocks unevenly.
Constants, cutoff threshold and stability
The 18 additions per level matter. Counting products and additions, the classical method uses operations and one Strassen level, seven classical products of size plus 18 block additions, uses . With the classical method costs , so one level helps only if , that is and . 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 with and 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
This is the matrix-multiplication exponent . We know : the lower bound follows from reading inputs, and the upper bound is an August 2026 result (Dupont et al., arXiv:2608.16884), not yet peer reviewed; the previous best was . Whether is unknown. For fixed-size multiplication , seven products are known to be optimal (Winograd, and Hopcroft and Kerr, 1971), so Strassen cannot be improved at . For , an algorithm with 23 products (Laderman, 1976) gives and is worse than Strassen; the best-known lower bound is 19.
matters beyond multiplication. Matrix inversion, determinant, rank, LU factorization and other linear-algebra problems reduce to multiplication and cost (Bunch and Hopcroft, 1974, for inversion and LU). Thus governs much of linear algebra’s complexity. It also appears in graphs: detecting a triangle costs through adjacency-matrix multiplication, and all shortest paths in an undirected unweighted graph cost using Seidel’s algorithm.
Modern treatment uses multilinear algebra. Matrix multiplication is a tensor and measures how its tensor rank grows with . A small-size algorithm with products yields recursively, just as Strassen does with and . 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 (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 with 47 products versus 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 points in the plane, which pair has the smallest Euclidean distance? Brute force compares pairs. The divide-and-conquer closest-pair algorithm (Shamos and Hoey, 1975) solves this in :
- Sort points by once and by once.
- Divide at median into left half and right half , with dividing line .
- Solve recursively: and are the halves’ minimum distances. Let .
- Combine: the best pair is either within a half, at distance , or crosses the dividing line. To cross with distance below , both points must lie within of the line, in the strip . Scan strip points in increasing order, comparing each only with subsequent points whose coordinate differs by less than .
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 is the union of two squares of side , one on each side of the dividing line. Points of in the left square are separated by at least . Divide the square into four closed squares of side and diagonal . Two points in one small square would be closer than . By the pigeonhole principle, the left square has at most 4 points of . The same holds on the right for , minimum distance . Points of lie left of or on the line, and lie right or on it, so every rectangle point is counted in its half’s square. Total .
∎Combination costs , with at most 7 comparisons per strip point, giving recurrence and by case 2. A frequently missed condition matters: scanning the strip ordered by requires points sorted by at every level. Sorting from scratch in each call makes combination cost and yields recurrence , of order . Instead merge by when recursion returns, as mergesort does, so each call returns its list sorted by without extra asymptotic cost. Check this in the implementation below.
is optimal in the algebraic decision-tree model by reduction from element uniqueness, requiring . 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, with including the outer face, and the fact that each interior face has 3 edges while the outer face has : , together with . Solving gives and .
For (a), let be the nearest neighbor of . The disk with diameter contains no other site inside. Otherwise angle would exceed and , contradicting the choice of . An empty disk through and has two sites on its boundary and none inside, characterizing Delaunay edges: .
For (b), let be an edge of a minimum spanning tree. In the same disk of diameter , an interior site would make both and shorter than . Replacing by or would produce a lighter tree, contradicting minimality. The disk is empty and .
∎The algorithmic consequence is strong. A Euclidean minimum spanning tree of points seems to require considering pairs, but it suffices to construct and run Kruskal on its edges, total cost . Delaunay triangulation can be built in by divide and conquer (Guibas and Stolfi, 1985: triangulate each half and stitch along the common lower tangent in linear time, giving ), by sweeping (Fortune, 1987), or randomized incremental construction. The figure uses simpler Bowyer-Watson, worst case, suitable for few points. Delaunay also maximizes the smallest angle among triangulations of , a reason for its use in finite-element meshes.
Inversion counting and Kendall distance
An inversion of sequence is a pair with . A sorted list has 0 inversions and a reversed list . 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 , while mergesort counts as it goes in :
- When merging sorted halves and , whenever an element of is taken before one of , it forms an inversion with every untaken element of .
- Total inversions comprise those in , those in , and crossings between halves. Count the latter during merge at constant cost per element, giving .
The relationship with rank correlation is an identity. If is Kendall distance between tie-free rankings of elements, Kendall coefficient is , ranging from for opposite rankings to for identical ones. This efficiently evaluates a recommender or search engine against a reference ordering.
Implementation from scratch
First examine recurrence behavior. Simulate exactly for and divide by the theorem’s prediction. If the predicted order is correct, the ratio stabilizes at a constant; otherwise it drifts.
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 in the fifth toward , slowly because . The last uses for and grows without bound: this is the earlier missing-logarithm error. Next compute the Akra-Bazzi exponent and simulate median-of-medians with floors:
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.
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 . With a cutoff of 8 to 16, Karatsuba wins at 64 digits and uses roughly one third as many operations at 512. Asymptotic 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 .
Now Strassen with NumPy. Blocks are views without copies, and the base case uses A @ B.
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: operations versus for direct multiplication, fewer. That cutoff saves of products, versus . Additions consume much of the gain; excessive recursion, such as cutoff 1 (), makes the method much worse. In float32, error grows with recursion depth, from for classical multiplication to 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 , merging by instead of resorting, and count inversions. Validate both against brute force.
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.
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
More than one answer may be correct.
Step 1 of 4. What is the level- term?
Step 1 of 3. What is known about distances between points in each square?
contar_inversiones(a) to return the number of pairs i < j with a[i] > a[j], counting strict inversions and excluding ties, in time. Do not modify the input list. Tests compare the result with brute force and check that element comparisons grow as ; for , 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 0Summary
- Solve by comparing with : leaves dominate in case 1, ; all levels weigh equally in case 2 with an extra factor; or the root dominates in case 3, , subject to regularity. The proof sums a geometric recursion tree.
- The master theorem misses gaps such as , failed regularity and unequal subproblems. Use level sums, substitution or Akra-Bazzi, and .
- Karatsuba, , gives . Strassen, , gives and works over noncommutative rings. Both need a cutoff; Strassen has worse numerical stability.
- , the matrix-multiplication exponent, satisfies , 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 and packing, at most 8 points in rectangle , for linear combination and if merging by instead of resorting.
- Delaunay and Voronoi: Delaunay contains nearest-neighbor and Euclidean MST edges, so that MST can be found in .
- Inversions: mergesort counts them in , giving Kendall distance between rankings.