Buku ini belum tersedia dalam Bahasa Indonesia. Edisi: English.
University Computer Science — Year 1 · Sarjana Tahun 1
21Divide and Conquer
Multiplying two numbers of 1000 digits by the method taught at school takes a million products of digits, one for each digit of the first number and each digit of the second. For centuries nobody expected to do better: every digit of one number must meet every digit of the other, it seems. It does not have to. Cutting each number in two halves and combining three products of halves, instead of four, gives a method whose cost grows like , and that is how long numbers are multiplied in practice. The idea behind it, cutting a problem into smaller ones of the same kind, has already given merge sort; this chapter turns it into a method and applies it to five problems.
You already know
The master theorem (Theorem 13.12) solves : if , if , and if ; a cost in place of gives the same orders. Merge sort (Definition 19.7) satisfies , hence . An inversion of a sequence is a pair of positions whose keys are out of order (Definition 19.3).
21.1 The method and its recurrences
Definition 21.1 (Divide and conquer)
A divide and conquer algorithm solves an instance of a problem in three steps: divide it into smaller instances of the same problem, solve each of them by a recursive call (or directly when it is small enough), and combine their solutions into a solution of the instance.
The method was met informally in the second book, on searching a sorted list and sorting by merging. Its analysis is always the same: if an instance of size is cut into instances of size , and dividing plus combining cost , the cost is , and the master theorem gives its order. The work lies in finding a cheap combine step, or in making small.
Counting inversions shows the three steps at their simplest. The inversions of a list are those inside its left half, those inside its right half, and those with one key on each side. The recursive calls count the first two kinds; the third kind is counted while merging the two sorted halves: when a key is taken from the right half, every key still waiting in the left half is larger and comes before it.
def sort_count(a):
"""(sorted copy of a, number of pairs i < j with a[i] > a[j])."""
if len(a) <= 1:
return list(a), 0
mid = len(a) // 2
left, x = sort_count(a[:mid]) # divide, and solve each half
right, y = sort_count(a[mid:])
merged, z, i = [], 0, 0 # combine: merge, counting the pairs split by mid
for r in right:
while i < len(left) and left[i] <= r:
merged.append(left[i])
i += 1
z += len(left) - i # r is smaller than every key left in `left`
merged.append(r)
merged += left[i:]
return merged, x + y + z
([1, 1, 2, 3, 4, 5, 6, 9], 8)
The combine step costs , so , against for testing every pair. Sorting was not asked for, but it makes the combine step cheap: a divide and conquer algorithm often returns more than the question, to make the next combination easy.
21.2 Karatsuba’s multiplication
A number of digits is a list of digits, least significant first. The school method adds the product of digit of and digit of into cell of the result, then propagates the carries.
def normalise(r):
"""Propagate carries in place: every cell back to 0..9 (cells may be negative)."""
carry = 0
for i in range(len(r)):
carry, r[i] = divmod(r[i] + carry, 10)
assert carry == 0, "the result does not fit"
return r
def school(a, b):
"""The school method: every digit of a times every digit of b."""
global products
r = [0] * (len(a) + len(b))
for i, x in enumerate(a):
for j, y in enumerate(b):
r[i + j] += x * y
products += len(b)
return normalise(r)
Cut each number in two halves of digits: and . Then
four products of halves, and is again: cutting alone gains nothing. But the middle term is a combination of the two others and of a single new product:
Method 21.2 (Karatsuba’s algorithm)
To multiply two numbers of digits, compute recursively , and , with the sign of , and return . Numbers of one digit are multiplied directly.
The differences and are less than : they have digits, like the halves, so that the three recursive calls are on numbers of digits exactly.
def difference(x, y):
"""(|x - y|, sign of x - y) for digit lists x, y of one length."""
sign = 1
for u, v in zip(reversed(x), reversed(y)): # compare from the top digit
if u != v:
sign = 1 if u > v else -1
break
if sign < 0:
x, y = y, x
return normalise([u - v for u, v in zip(x, y)]), sign
def karatsuba(a, b, cutoff=1):
"""Product of two digit lists of one length n, a power of 2; 2n digits."""
n = len(a)
if n <= cutoff:
return school(a, b)
m = n // 2
a0, a1, b0, b1 = a[:m], a[m:], b[:m], b[m:] # a = a1 * 10^m + a0
z0 = karatsuba(a0, b0, cutoff)
z2 = karatsuba(a1, b1, cutoff)
da, sa = difference(a1, a0)
db, sb = difference(b1, b0)
z1 = karatsuba(da, db, cutoff) # (a1 - a0)(b1 - b0) = sa * sb * z1
r = [0] * (2 * n)
for i in range(2 * m): # a1 b0 + a0 b1 = z2 + z0 - (a1 - a0)(b1 - b0)
r[i] += z0[i]
r[i + m] += z0[i] + z2[i] - sa * sb * z1[i]
r[i + 2 * m] += z2[i]
return normalise(r)
The combine loop adds and subtracts into cells that may go negative; normalise takes them back to digits with floor division, and its assertion checks that the result fits in digits, as the product of two -digit numbers must.
The recurrence is now , and : the master theorem gives , with . The program counts the products exactly.
$ python karatsuba.py
school : 1234 x 5678 = 7006652, 16 digit products
karatsuba: 1234 x 5678 = 7006652, 9 digit products
n school karatsuba 3^k
1 1 1 1
2 4 3 3
4 16 9 9
8 64 27 27
16 256 81 81
32 1024 243 243
64 4096 729 729
128 16384 2187 2187
256 65536 6561 6561
512 262144 19683 19683
1024 1048576 59049 59049
Fewer products do not mean less time: each call also pays for two differences, a combine loop and its carries, and a call costs much more than a product of digits. Below some size, the school method wins. A cutoff makes Karatsuba’s method fall back on the school method for numbers of at most that many digits.
$ python karatsuba_timing.py
n school cutoff 1 cutoff 8 cutoff 32
16 8 98 12 8
32 29 314 47 35
64 113 918 142 99
128 418 2893 489 339
256 1773 9019 1534 1047
512 9412 26366 4425 3204
1024 39270 79194 14331 9772
2048 167668 237497 41350 29815
History — Three products instead of four
The method was published by Karatsuba and Ofman in 1962. In 1969, Strassen applied the same idea to matrices: two block matrices can be multiplied with 7 block products instead of 8, which gives , about operations, for matrices.
Facts as of 2026
CPython multiplies its integers by the school method unless both have more than 70 internal digits, of 30 bits each, about 630 decimal digits; above that it uses Karatsuba’s method. This is read in its source code, and such thresholds change between versions.
21.3 The closest pair of points
Definition 21.3 (Closest-pair problem)
The closest-pair problem asks, for distinct points of the plane, for the smallest distance between two of them.
Comparing every pair takes distances. Divide and conquer sorts the points by , cuts them by a vertical line through the median , and solves both halves: is the smaller of the two answers. A closer pair can only have one point on each side, both within of the line: in the strip of width around it.
Proposition 21.4 (Seven neighbours suffice)
Sort the points of the strip by . If two of them, before , are less than apart, then is one of the seven points that follow .
Proof. All the points that follow and are within of it lie in the rectangle of width and height whose bottom edge passes through , centred on the line. Cut this rectangle into eight squares of side , four on each side of the line. Two points in one square are at most apart, and on one side of the line, which contradicts the definition of : each square holds at most one point. With itself, the rectangle holds at most eight points, so at most seven points come after before the first one with . ∎
def solve(px):
"""(smallest distance, the points of px sorted by y); px is sorted by x."""
n = len(px)
if n <= 3:
best = min((d(p, q) for i, p in enumerate(px) for q in px[i + 1:]), default=inf)
return best, sorted(px, key=lambda p: p[1])
mid = n // 2
x_mid = px[mid][0]
dl, left = solve(px[:mid])
dr, right = solve(px[mid:])
delta = min(dl, dr)
py = merge_by_y(left, right)
strip = [p for p in py if abs(p[0] - x_mid) < delta] # still sorted by y
for i, p in enumerate(strip):
for q in strip[i + 1:i + 8]: # at most 7 points can follow within delta
if q[1] - p[1] >= delta:
break
delta = min(delta, d(p, q))
return delta, py
Each call returns its points sorted by , merged from the two halves, so that the strip is sorted without sorting: the combine step costs and the whole . On the town’s 30 places and on random points:
$ python closest_pair.py
town: 30 places; closest: Cinema and Football Ground, 405 m
n divide and conquer brute force
250 260 31125
500 572 124750
1000 1127 499500
2000 2308 1999000
On random points the strip is thin and holds few points: barely more than one distance per point.
21.4 Selection in linear time
Definition 21.5 (Selection problem, quickselect, median of medians)
The selection problem asks for the key of rank of keys, the one that would be at position if they were sorted; the median is the key of rank . Quickselect partitions the keys around a pivot, as quicksort does, and goes on in the one part that holds rank . The median of medians chooses as pivot the median of the medians of groups of five keys, found by a recursive call.
Sorting answers in ; selection needs less. Quickselect makes one recursive call instead of two, so with pivots that halve the keys its cost is partition steps. With bad pivots it is quadratic, like quicksort.
def split(a, pivot):
"""The keys of a below, equal to and above pivot."""
low, high = [x for x in a if less(x, pivot)], [x for x in a if less(pivot, x)]
return low, len(a) - len(low) - len(high), high
def quickselect(a, k, rng=None):
"""The key of rank k (0 = smallest); pivot: the last key, or a random one."""
while True:
pivot = a[-1] if rng is None else rng.choice(a)
low, equal, high = split(a, pivot)
if k < len(low):
a = low
elif k < len(low) + equal:
return pivot
else:
a, k = high, k - len(low) - equal
def mom_select(a, k):
"""The key of rank k, with the median of the medians of groups of five as pivot."""
if len(a) <= 5:
return sort5(a)[k]
groups = [a[i:i + 5] for i in range(0, len(a), 5)]
medians = [sort5(g)[(len(g) - 1) // 2] for g in groups]
pivot = mom_select(medians, (len(medians) - 1) // 2)
low, equal, high = split(a, pivot)
if k < len(low):
return mom_select(low, k)
if k < len(low) + equal:
return pivot
return mom_select(high, k - len(low) - equal)
$ python selection.py
n quick, sorted quick, random quick, rnd pivot mom, sorted mom, random
1000 750500 6804 6482 8359 10754
2000 3001000 10884 6696 17183 21081
4000 12002000 18484 21652 35095 43256
8000 48004000 40984 42240 71099 88584
On a sorted list, the last key as pivot is the largest, and quickselect removes one key per round: rounds on , , …, keys, about keys partitioned in all, two comparisons per key: about , the 750 500 of the table for . A random pivot gives a linear cost on average. The median of medians gives it in the worst case.
Theorem 21.6 (Selection in linear time)
The median of medians finds the key of rank of keys in comparisons.
Proof. Of the medians, at least are at most the pivot, and each of their groups, except perhaps the pivot’s own and a last incomplete one, holds three keys at most the pivot. So at least keys are at most the pivot; likewise at least that many are at least the pivot. The recursive call on one side therefore receives at most keys. Sorting the groups and partitioning cost at most comparisons for a constant , so
Suppose for , with and , and bounded by on small sizes by taking larger if needed. Then , and for , so . ∎
The proof works because : the two calls together receive less than the whole. Groups of three fail this test (Exercise 21.10). The constant is large: eight to eleven comparisons per key in Output 21.5, against three to seven for quickselect on shuffled keys or with random pivots. A practical routine runs quickselect and can fall back on a guaranteed method when the recursion goes too deep, as introsort does for sorting. The algorithm is due to Blum, Floyd, Pratt, Rivest and Tarjan, in 1973.
21.5 Dichotomy on the answer, and meeting in the middle
Binary search halves a sorted array (Proposition 12.6). It halves anything ordered, including the answers to a question.
Definition 21.7 (Monotone predicate, dichotomy on the answer)
A predicate on the integers is monotone if implies : false up to some point, true after it. A dichotomy on the answer finds the smallest in with , knowing , by binary search on , with evaluations of .
The town wants to cover its 30 places with snow-clearing zones, each a band of the same width from west to east. For a given width, a greedy pass decides whether bands suffice: start a band at the westernmost place not yet covered. A larger width never needs more bands, so the predicate is monotone, and the smallest width is found by dichotomy.
def covers(xs, k, length):
"""Can k segments of this length cover the sorted points xs? (greedy)"""
used, end = 0, None
for x in xs:
if end is None or x > end: # x is not covered: a new segment starts at x
used += 1
end = x + length
return used <= k
def smallest_length(xs, k):
"""The smallest integer length that works: covers is false below it, true above."""
lo, hi = 0, xs[-1] - xs[0] # covers(hi) is true: one segment suffices
calls = 0
while lo < hi: # the answer is in [lo, hi]
mid = (lo + hi) // 2
calls += 1
if covers(xs, k, mid):
hi = mid
else:
lo = mid + 1
return lo, calls
$ python segments.py
30 places, x from 33 to 5657 m
k length (m) calls
1 5624 12
2 2786 12
3 1824 12
4 1333 12
5 921 12
6 772 12
7 667 13
8 612 13
Twelve or thirteen tests decide among 5625 widths. The method applies whenever checking an answer is easier than finding it, and the check is monotone.
Definition 21.8 (Meet in the middle)
Meeting in the middle splits a search over choices into two halves, lists the partial results of each half, and finds the compatible pairs by sorting or hashing, instead of trying every combination.
The subset-sum search of Chapter 20 visits up to subsets. Split the values into two halves: each has subset sums; a subset of all the values sums to the target exactly when its left part sums to and its right part to . A table of how many right subsets give each sum answers that question for all .
def all_sums(values):
"""The sums of the 2^len(values) subsets (with repetitions)."""
sums = [0]
for v in values:
sums += [s + v for s in sums] # each subset without v, then with v
return sums
def count(values, target):
"""(number of subsets summing to target, sums computed)."""
half = len(values) // 2
left, right = all_sums(values[:half]), all_sums(values[half:])
right_count = Counter(right) # how many right subsets give each sum
found = sum(right_count[target - s] for s in left)
return found, len(left) + len(right)
$ python meet_middle.py
n lists subsets 2^n sums computed
16 9 65536 512
24 31 16777216 8192
32 147 4294967296 131072
40 459 1099511627776 2097152
The counts for 16 and 24 books are those found by backtracking in Output 20.6. The cost is sums and table operations, with a table of the same size: memory is traded for time. Forty books are reached with two million sums, where the full tree has a trillion leaves.
21.6 Exercises
Exercise 21.1 ★
List the inversions of and check the count of Output 21.1. How many are counted by the top-level merge?
Solution
Solution of Exercise 21.1.
The 3 is larger than both 1s and the 2; the 4 than the second 1 and the 2; the 5 than the 2; the 9 than the 2 and the 6: . The left half has 3 inversions, the right half has 3, and the top-level merge counts the 2 pairs across the middle, and .
Exercise 21.2 ★
Give the three products of halves that Karatsuba’s method computes at the top level for , the sign , and the result.
Solution
Solution of Exercise 21.2.
, , , . , , , and . The middle term is (indeed ), and .
Exercise 21.3 ★
Run quickselect by hand on with and the last key as pivot: give the pivots and the parts kept.
Solution
Solution of Exercise 21.3.
Pivot 5: below , above ; rank 5 is above, at rank there. Pivot 8: below , one key equal; rank 1 is the pivot: the answer is 8, the key of rank 5 of .
Exercise 21.4 ★
For the points and , give the values of covers for every width, and the widths the dichotomy tests.
Solution
Solution of Exercise 21.4.
covers is false for the widths 0 to 9 (at width 9 the bands , and are needed) and true from 10 on ( and ). The dichotomy on tests 10 (true), 5, 8 and 9 (false), and returns 10 after four tests.
Exercise 21.5 ★★
This version compares each point of the strip with the next one only. Explain the counterexample it finds.
def closest(px): # px sorted by x
if len(px) <= 3:
return min(dist(p, q) for i, p in enumerate(px) for q in px[i + 1:])
mid = len(px) // 2
delta = min(closest(px[:mid]), closest(px[mid:]))
strip = [p for p in px if abs(p[0] - px[mid][0]) < delta]
strip.sort(key=lambda p: p[1])
for p, q in zip(strip, strip[1:]): # only neighbours in the y order
delta = min(delta, dist(p, q))
return delta
trial 127: [(0, 0), (4, 6), (5, 8), (7, 2), (9, 7)]
returned 4.123, true 2.236
Solution
Solution of Exercise 21.5.
The halves give , and the strip around holds , , and . In the order they are , , , : the closest pair, and , at , is separated by , which is far from both in . Neighbours in the order are not enough: the proposition allows up to seven points between, and the loop must go on while the distance is below .
Exercise 21.6 ★★
This dichotomy computes a cube root with an absolute tolerance. Explain why it never ends for , and repair it.
def cube_root(y, tolerance=1e-12, limit=2000):
lo, hi = 0.0, max(1.0, y)
steps = 0
while hi - lo > tolerance:
mid = (lo + hi) / 2
if mid**3 < y:
lo = mid
else:
hi = mid
steps += 1
if steps == limit: # a guard, so that the demonstration stops
print(f"y = {y:g}: stuck after {steps} steps, lo = {lo!r}, hi = {hi!r},"
f" mid == hi: {mid == hi}")
return None
return lo
y = 2: 1.2599210498947286 after the loop
y = 1e+06: 99.9999999999994 after the loop
y = 1e+15: stuck after 2000 steps, lo = 99999.99999999999, hi = 100000.0, mid == hi: True
Solution
Solution of Exercise 21.6.
Near , two consecutive doubles differ by , more than the tolerance. When and are consecutive doubles, their mean rounds to one of them, the loop assigns it, and nothing changes: the output shows . Repairs: stop when equals or ; or use a relative tolerance, ; or run a fixed number of halvings (about 110 here cover the 50 bits of the initial width and the 53 bits of precision).
Exercise 21.7 ★★
Compute the largest sum of a non-empty slice of a list by divide and conquer, in , and test it against a linear method that keeps the best sum ending at each position.
Solution
Solution of Exercise 21.7.
def best(a, lo=0, hi=None):
"""The largest sum of a non-empty slice of a[lo:hi]."""
if hi is None:
hi = len(a)
if hi - lo == 1:
return a[lo]
mid = (lo + hi) // 2
left_end, s = a[mid - 1], 0 # best slice ending at mid - 1
for i in range(mid - 1, lo - 1, -1):
s += a[i]
left_end = max(left_end, s)
right_start, s = a[mid], 0 # best slice starting at mid
for i in range(mid, hi):
s += a[i]
right_start = max(right_start, s)
return max(best(a, lo, mid), best(a, mid, hi), left_end + right_start)
A best slice lies in the left half, in the right half, or across the middle, where it is a best slice ending at followed by a best slice starting at ; both are found by one scan. So . The test compares with Kadane’s linear scan and with all slices on 200 random lists.
Exercise 21.8 ★★
A majority key of a list is held by more than half of its positions. Find it, or report that there is none, by divide and conquer in .
Solution
Solution of Exercise 21.8.
def majority(a):
"""The majority key of a, or None."""
if len(a) == 1:
return a[0]
mid = len(a) // 2
candidates = {majority(a[:mid]), majority(a[mid:])} - {None}
for c in candidates: # a majority of a is a majority of one half
if 2 * a.count(c) > len(a):
return c
return None
If a key held at most half of each half, it would hold at most positions: a majority key of the list is a majority key of one half. So it is one of the at most two candidates returned by the halves, and counting each costs : .
Exercise 21.9 ★★
Karatsuba’s method pads numbers of digits to the next power of 2. Show that it makes fewer than digit products, and that with a cutoff it makes on digits.
Solution
Solution of Exercise 21.9.
For numbers of digits, multiply takes the smallest power , so and . With a cutoff , for and , the school method’s count: .
Exercise 21.10 ★★★
Show that the median of medians with groups of three gives the recurrence , and that this recurrence does not imply : its solution with equality is .
Solution
Solution of Exercise 21.10.
With groups of three, at least half of the medians are at most the pivot, and each of their groups holds two keys at most the pivot: about keys on each side, so the recursive call receives up to , and . Now : no level of the recursion tree is smaller than the one above. Take and suppose for . Then
so ; with groups of three the method is not proved linear.
Exercise 21.11 ★★★
Buildings are rectangles standing on a line. Compute the skyline, the list of points where the visible height changes, by divide and conquer in .
Solution
Solution of Exercise 21.11.
def skyline(buildings):
if not buildings:
return []
if len(buildings) == 1:
left, right, h = buildings[0]
return [(left, h), (right, 0)]
mid = len(buildings) // 2
return merge(skyline(buildings[:mid]), skyline(buildings[mid:]))
def merge(a, b):
"""Merge two outlines: at each x, the higher of the two current heights."""
out, i, j, ha, hb = [], 0, 0, 0, 0
while i < len(a) or j < len(b):
xa = a[i][0] if i < len(a) else float("inf")
x = min(xa, b[j][0] if j < len(b) else float("inf"))
if i < len(a) and a[i][0] == x:
ha = a[i][1]
i += 1
if j < len(b) and b[j][0] == x:
hb = b[j][1]
j += 1
h = max(ha, hb)
if not out or out[-1][1] != h:
out.append((x, h))
return out
Merging two outlines walks both lists once, keeping the current height of each, and records the larger one wherever it changes: for outlines of points. Hence . The test compares the outline’s height at every integer abscissa with the highest building standing there.
Exercise 21.12 ★★★
Find four positions of a list whose keys sum to a target in , by meeting in the middle on the sums of pairs, and prove the method correct.
Solution
Solution of Exercise 21.12.
def four_sum(a, target):
"""Positions (i, j, k, m), i < j < k < m, of a solution, or None."""
n = len(a)
latest = {} # sum -> the pair (k, m) with that sum and the largest k
for k in range(n):
for m in range(k + 1, n):
latest[a[k] + a[m]] = (k, m) # k grows: the last kept is the latest
sums = sorted(latest)
for i in range(n):
for j in range(i + 1, n):
want = target - a[i] - a[j]
p = bisect_left(sums, want)
if p < len(sums) and sums[p] == want and latest[want][0] > j:
return (i, j) + latest[want]
return None
The table keeps, for each sum of two keys, the pair with that sum and the largest . If a solution exists, then when the loops reach , the sum is in the table with a pair whose first position is at least : a solution is returned. Conversely a returned quadruple has the target sum and increasing positions. The table takes steps, its sorting , and the binary searches . The test compares with all quadruples on random lists.
21.7 Problem: Multiplying long numbers
Problem 21.1
Weekend problem — Multiplying long numbers
The listings of this chapter multiply numbers given as lists of decimal digits. The problem counts their work exactly, then reads their measured times (Outputs 21.2 and 21.3).
Part I — The school method.
- How many digit products does the school method make for two numbers of digits? Check with the output.
- Show that a cell of
r, before the carries, holds at most . - Show that propagating the carries once, at the end, costs and gives the right digits.
- Why does the result of two -digit numbers fit in digits?
- By what factor does the school method’s time grow when doubles, according to the table? What does the model predict?
- How many digit products does the opening’s multiplication of two 1000-digit numbers take?
Part II — Karatsuba’s identity.
- Expand with , .
- Prove .
- Why do and have at most digits?
- What does
differencereturn, and why does it compare from the top digit? - The combine loop leaves cells that may be negative. Why does
normalisestill give the right digits? - Write the recurrence for the number of digit products, a power of 2.
Part III — Exact counts.
- Prove .
- Show that for .
- Compare with .
- Show that the other work of one call on digits is , and that the total work is still .
- With a cutoff , how many digit products are made on digits (Exercise 21.9)? Give the count for and .
- Which cutoff minimises the number of digit products? Why is a larger one used anyway?
Part IV — Where it pays, on this machine.
- Without a cutoff, by what factor is Karatsuba’s method slower than the school method at each of the table? How does that factor change when doubles?
- Estimate from that trend the size from which Karatsuba’s method without a cutoff would win.
- From which of the table does Karatsuba’s method with cutoff 8, then with cutoff 32, beat the school method?
- By what factor does the time with cutoff 32 grow when doubles at the end of the table? Compare with and .
- CPython’s cutoff is 70 digits of 30 bits. How many decimal digits is that?
- State the named result, Karatsuba’s count.
Solution
Solution of Problem 21.1.
1. , one for each pair of digits: 1 048 576 for .
2. Cell receives the products with : at most one for each , so at most products, each at most .
3. One pass over cells, with a carry at most : steps on numbers of a few bytes. Each step replaces by its last digit and carries the rest to cell , which keeps unchanged; at the end every cell is a digit.
4. , so .
5. From 9412 to 39 270 to 167 668: by about 4.2 per doubling; the model predicts 4.
6. A million, ; the program pads to 1024 digits and makes 1 048 576.
7. .
8. ; move the two middle terms to the other side.
9. , so .
10. The digits of , as a list of the same length, and the sign of . Between two numbers of the same length, the first digit that differs from the top decides which is larger.
11. The loop makes equal to the product. divmod writes any integer, negative or not, as with , so each step keeps the sum and leaves a digit; the product is in , so the last carry is 0 and the cells are its digits.
12. and .
13. , and .
14. .
15. against 1 048 576: about 18 times fewer.
16. The slices, the two differences, the combine loop and normalise each take steps. So , and since the master theorem gives : the leaves dominate, and the additions do not change the order.
17. ; for and , .
18. The cutoff 1: each level handed to the school method multiplies the count by . A larger cutoff is used because a call, with its lists and its carries, costs far more than a digit product: the time is not the count.
19. 12.3, 10.8, 8.1, 6.9, 5.1, 2.8, 2.0, 1.4 for to 2048. The factor falls by about 0.7 per doubling at the end, close to the expected when one time grows like and the other like .
20. With factors of about at 4096 digits and 0.8 at 8192: from about 5000 digits.
21. With cutoff 8, from 256 digits (1534 against 1773 microseconds); with cutoff 32, from 64 digits (99 against 113).
22. and : close to 3, where the school method grows by 4.
23. bits, and decimal digits.
24. Karatsuba’s count: Karatsuba’s method multiplies two numbers of digits with exactly digit products, that is for (questions 12 to 14), the counts printed by the program in Output 21.2; its whole cost is (question 16).