Ilmu Komputer · Buku 3 · Sarjana Tahun 1

University Computer Science — Year 1

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 n1.585n^{1.585}, 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 T(n)=aT(n/b)+nkT(n) = aT(n/b) + n^k: T(n)=Θ(nk)T(n) = \Theta(n^k) if a<bka < b^k, Θ(nklog⁡n)\Theta(n^k \log n) if a=bka = b^k, and Θ(nlog⁡ba)\Theta(n^{\log_b a}) if a>bka > b^k; a cost Θ(nk)\Theta(n^k) in place of nkn^k gives the same orders. Merge sort (Definition 19.7) satisfies T(n)=2T(n/2)+Θ(n)T(n) = 2T(n/2) + \Theta(n), hence Θ(nlog⁡n)\Theta(n \log n). An inversion of a sequence is a pair of positions i<ji < j 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 nn is cut into aa instances of size n/bn/b, and dividing plus combining cost f(n)f(n), the cost is T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n), and the master theorem gives its order. The work lies in finding a cheap combine step, or in making aa 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
Listing 21.1. Counting inversions while sorting code/bachelor-1/21-divide-and-conquer/listings/inversions.py
([1, 1, 2, 3, 4, 5, 6, 9], 8)
Output 21.1. The sorted list and its 8 inversions. Some lines are left out.

The combine step costs Θ(n)\Theta(n), so T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n), against Θ(n2)\Theta(n^2) 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 nn digits is a list of digits, least significant first. The school method adds the product of digit ii of aa and digit jj of bb into cell i+ji + j 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)
Listing 21.2. Carries, and the school method with its counter of digit products code/bachelor-1/21-divide-and-conquer/listings/digits.py

Cut each number in two halves of m=n/2m = n/2 digits: a=a110m+a0a = a_1 10^m + a_0 and b=b110m+b0b = b_1 10^m + b_0. Then

ab=a1b1102m+(a1b0+a0b1)10m+a0b0,ab = a_1 b_1 10^{2m} + (a_1 b_0 + a_0 b_1) 10^m + a_0 b_0,

four products of halves, and T(n)=4T(n/2)+Θ(n)T(n) = 4T(n/2) + \Theta(n) is Θ(n2)\Theta(n^2) again: cutting alone gains nothing. But the middle term is a combination of the two others and of a single new product:

a1b0+a0b1=a1b1+a0b0−(a1−a0)(b1−b0).a_1 b_0 + a_0 b_1 = a_1 b_1 + a_0 b_0 - (a_1 - a_0)(b_1 - b_0).

Method 21.2 (Karatsuba’s algorithm)

To multiply two numbers of n=2mn = 2m digits, compute recursively z2=a1b1z_2 = a_1 b_1, z0=a0b0z_0 = a_0 b_0 and z1=∣a1−a0∣⋅∣b1−b0∣z_1 = |a_1 - a_0| \cdot |b_1 - b_0|, with ss the sign of (a1−a0)(b1−b0)(a_1 - a_0)(b_1 - b_0), and return z2102m+(z2+z0−sz1)10m+z0z_2 10^{2m} + (z_2 + z_0 - s z_1) 10^m + z_0. Numbers of one digit are multiplied directly.

The differences ∣a1−a0∣|a_1 - a_0| and ∣b1−b0∣|b_1 - b_0| are less than 10m10^m: they have mm digits, like the halves, so that the three recursive calls are on numbers of mm 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)
Listing 21.3. The difference of two halves, and Karatsuba’s multiplication code/bachelor-1/21-divide-and-conquer/listings/karatsuba.py

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 2n2n digits, as the product of two nn-digit numbers must.

The recursion tree of Karatsuba’s algorithm on n = 2k digits: three children per node. Level i holds 3i calls on n/2i digits, and the combine work of the level is (3/2)i (n), growing to the leaves. The same cut with four products (in red) has 4i calls at level i.
The recursion tree of Karatsuba’s algorithm on n=2kn = 2^k digits: three children per node. Level ii holds 3i3^i calls on n/2in/2^i digits, and the combine work of the level is (3/2)iΘ(n)(3/2)^i \Theta(n), growing to the leaves. The same cut with four products (in red) has 4i4^i calls at level ii.

The recurrence is now T(n)=3T(n/2)+Θ(n)T(n) = 3T(n/2) + \Theta(n), and 3>213 > 2^1: the master theorem gives Θ(nlog⁡23)\Theta(n^{\log_2 3}), with log⁡23≈1.585\log_2 3 \approx 1.585. 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
Output 21.2. Digit products of the two methods, on a small example and on nn nines times nn nines.

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
Output 21.3. Microseconds per product of two random nn-digit numbers, on the author’s laptop, for the school method and Karatsuba’s with three cutoffs.
Left: digit products counted in ; the slopes are 2 and _2 3. Right: the measured times of ; without a cutoff, Karatsuba’s method is still slower at 2048 digits, with a cutoff of 32 it is faster from 64 digits on. Left: digit products counted in ; the slopes are 2 and _2 3. Right: the measured times of ; without a cutoff, Karatsuba’s method is still slower at 2048 digits, with a cutoff of 32 it is faster from 64 digits on.
Left: digit products counted in Output 21.2; the slopes are 2 and log⁡23\log_2 3. Right: the measured times of Output 21.3; without a cutoff, Karatsuba’s method is still slower at 2048 digits, with a cutoff of 32 it is faster from 64 digits on.

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 2×22 \times 2 block matrices can be multiplied with 7 block products instead of 8, which gives Θ(nlog⁡27)\Theta(n^{\log_2 7}), about n2.81n^{2.81} operations, for n×nn \times n 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 n≥2n \geq 2 distinct points of the plane, for the smallest distance between two of them.

Comparing every pair takes n(n−1)/2n(n - 1)/2 distances. Divide and conquer sorts the points by xx, cuts them by a vertical line through the median xx, and solves both halves: δ\delta is the smaller of the two answers. A closer pair can only have one point on each side, both within δ\delta of the line: in the strip of width 2δ2\delta around it.

Proposition 21.4 (Seven neighbours suffice)

Sort the points of the strip by yy. If two of them, pp before qq, are less than δ\delta apart, then qq is one of the seven points that follow pp.

Proof. All the points that follow pp and are within δ\delta of it lie in the rectangle of width 2δ2\delta and height δ\delta whose bottom edge passes through pp, centred on the line. Cut this rectangle into eight squares of side δ/2\delta/2, four on each side of the line. Two points in one square are at most δ/2<δ\delta/\sqrt{2} < \delta apart, and on one side of the line, which contradicts the definition of δ\delta: each square holds at most one point. With pp itself, the rectangle holds at most eight points, so at most seven points come after pp before the first one with y≥py+δy \geq p_y + \delta. ∎

The strip argument. The points that follow p in the y order and are within  of it lie in the shaded 2 × rectangle; each of its eight squares holds at most one point. Points on one side are at least  apart; the point just right of the line is the one that can beat .
The strip argument. The points that follow pp in the yy order and are within δ\delta of it lie in the shaded 2δ×δ2\delta \times \delta rectangle; each of its eight squares holds at most one point. Points on one side are at least δ\delta apart; the point just right of the line is the one that can beat δ\delta.
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
Listing 21.4. The closest pair, returning the points sorted by yy for the caller’s strip code/bachelor-1/21-divide-and-conquer/listings/closest_pair.py

Each call returns its points sorted by yy, merged from the two halves, so that the strip is sorted without sorting: the combine step costs Θ(n)\Theta(n) and the whole Θ(nlog⁡n)\Theta(n \log n). 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
Output 21.4. The closest pair of the town’s places, and distances computed on random points, against brute force.

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 kk of nn keys, the one that would be at position kk if they were sorted; the median is the key of rank ⌊(n−1)/2⌋\lfloor (n - 1)/2 \rfloor. Quickselect partitions the keys around a pivot, as quicksort does, and goes on in the one part that holds rank kk. 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 Θ(nlog⁡n)\Theta(n \log n); selection needs less. Quickselect makes one recursive call instead of two, so with pivots that halve the keys its cost is n+n/2+n/4+⋯≤2nn + n/2 + n/4 + \dots \leq 2n 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)
Listing 21.5. Partition, quickselect, and the median of medians code/bachelor-1/21-divide-and-conquer/listings/selection.py
$ 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
Output 21.5. Comparisons to find the key of rank n/2n/2 (the upper median) of nn keys, sorted or shuffled.

On a sorted list, the last key as pivot is the largest, and quickselect removes one key per round: rounds on nn, n−1n - 1, …, n/2n/2 keys, about 3n2/83n^2/8 keys partitioned in all, two comparisons per key: about 3n2/43n^2/4, the 750 500 of the table for n=1000n = 1000. A random pivot gives a linear cost on average. The median of medians gives it in the worst case.

Thirty-five keys in seven columns of five, columns ordered by their median; the circled key, the median of the medians, is the pivot. The shaded block below and left holds keys no larger than the pivot, the one above and right keys no smaller: each about 3/10 of all keys.
Thirty-five keys in seven columns of five, columns ordered by their median; the circled key, the median of the medians, is the pivot. The shaded block below and left holds keys no larger than the pivot, the one above and right keys no smaller: each about 3/103/10 of all keys.

Theorem 21.6 (Selection in linear time)

The median of medians finds the key of rank kk of nn keys in O(n)O(n) comparisons.

Proof. Of the g=⌈n/5⌉g = \lceil n/5 \rceil medians, at least ⌈g/2⌉\lceil g/2 \rceil 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 3(⌈g/2⌉−2)≥3n/10−63(\lceil g/2 \rceil - 2) \geq 3n/10 - 6 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 7n/10+67n/10 + 6 keys. Sorting the groups and partitioning cost at most anan comparisons for a constant aa, so

T(n)≤T(⌈n/5⌉)+T(7n/10+6)+an.T(n) \leq T(\lceil n/5 \rceil) + T(7n/10 + 6) + an.

Suppose T(j)≤cjT(j) \leq cj for j<nj < n, with n≥140n \geq 140 and c=20ac = 20a, and TT bounded by cjcj on small sizes by taking cc larger if needed. Then T(n)≤c(n/5+1)+c(7n/10+6)+an=cn−c(n/10−7)+anT(n) \leq c(n/5 + 1) + c(7n/10 + 6) + an = cn - c(n/10 - 7) + an, and n/10−7≥n/20n/10 - 7 \geq n/20 for n≥140n \geq 140, so T(n)≤cn−cn/20+an=cnT(n) \leq cn - cn/20 + an = cn. ∎

The proof works because 1/5+7/10<11/5 + 7/10 < 1: 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 PP on the integers is monotone if P(x)P(x) implies P(x+1)P(x + 1): false up to some point, true after it. A dichotomy on the answer finds the smallest xx in [lo,hi][lo, hi] with P(x)P(x), knowing P(hi)P(hi), by binary search on xx, with ⌈log⁡2(hi−lo+1)⌉\lceil \log_2 (hi - lo + 1) \rceil evaluations of PP.

The town wants to cover its 30 places with kk snow-clearing zones, each a band of the same width from west to east. For a given width, a greedy pass decides whether kk 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
Listing 21.6. The greedy test and the dichotomy on the width code/bachelor-1/21-divide-and-conquer/listings/segments.py
$ 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
Output 21.6. The smallest width of kk bands covering the town’s places, and the number of tests.

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 2n2^n subsets. Split the nn values into two halves: each has 2n/22^{n/2} subset sums; a subset of all the values sums to the target exactly when its left part sums to ss and its right part to target−s\mathit{target} - s. A table of how many right subsets give each sum answers that question for all ss.

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)
Listing 21.7. Subset sum by meeting in the middle code/bachelor-1/21-divide-and-conquer/listings/meet_middle.py
$ 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
Output 21.7. Reading lists of exactly 1000 pages from the first nn books.

The counts for 16 and 24 books are those found by backtracking in Output 20.6. The cost is Θ(2n/2)\Theta(2^{n/2}) 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 [3,1,4,1,5,9,2,6][3, 1, 4, 1, 5, 9, 2, 6] 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: 3+2+1+2=83 + 2 + 1 + 2 = 8. The left half [3,1,4,1][3, 1, 4, 1] has 3 inversions, the right half [5,9,2,6][5, 9, 2, 6] has 3, and the top-level merge counts the 2 pairs across the middle, (3,2)(3, 2) and (4,2)(4, 2).

Exercise 21.2 ★

Give the three products of halves that Karatsuba’s method computes at the top level for 1234×56781234 \times 5678, the sign ss, and the result.

Solution

Solution of Exercise 21.2.

a1=12a_1 = 12, a0=34a_0 = 34, b1=56b_1 = 56, b0=78b_0 = 78. z2=12×56=672z_2 = 12 \times 56 = 672, z0=34×78=2652z_0 = 34 \times 78 = 2652, z1=∣12−34∣⋅∣56−78∣=22×22=484z_1 = |12 - 34| \cdot |56 - 78| = 22 \times 22 = 484, and s=(−1)(−1)=1s = (-1)(-1) = 1. The middle term is 672+2652−484=2840672 + 2652 - 484 = 2840 (indeed 12×78+34×56=936+190412 \times 78 + 34 \times 56 = 936 + 1904), and 672⋅104+2840⋅102+2652=7 006 652672 \cdot 10^4 + 2840 \cdot 10^2 + 2652 = 7\,006\,652.

Exercise 21.3 ★

Run quickselect by hand on [7,2,9,4,1,8,5][7, 2, 9, 4, 1, 8, 5] with k=5k = 5 and the last key as pivot: give the pivots and the parts kept.

Solution

Solution of Exercise 21.3.

Pivot 5: below [2,4,1][2, 4, 1], above [7,9,8][7, 9, 8]; rank 5 is above, at rank 5−4=15 - 4 = 1 there. Pivot 8: below [7][7], one key equal; rank 1 is the pivot: the answer is 8, the key of rank 5 of 1,2,4,5,7,8,91, 2, 4, 5, 7, 8, 9.

Exercise 21.4 ★

For the points 0,3,4,10,12,200, 3, 4, 10, 12, 20 and k=2k = 2, 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 [0,9][0, 9], [10,19][10, 19] and [20,29][20, 29] are needed) and true from 10 on ([0,10][0, 10] and [12,22][12, 22]). The dichotomy on [0,20][0, 20] 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
Listing 21.8. A strip checked too lightly code/bachelor-1/21-divide-and-conquer/listings/exo_strip_bug.py
trial 127: [(0, 0), (4, 6), (5, 8), (7, 2), (9, 7)]
returned 4.123, true 2.236
Output 21.8. Against brute force. Some lines are left out.
Solution

Solution of Exercise 21.5.

The halves give δ≈4.123\delta \approx 4.123, and the strip around x=5x = 5 holds (4,6)(4, 6), (5,8)(5, 8), (7,2)(7, 2) and (9,7)(9, 7). In the yy order they are (7,2)(7, 2), (4,6)(4, 6), (9,7)(9, 7), (5,8)(5, 8): the closest pair, (4,6)(4, 6) and (5,8)(5, 8), at 5≈2.236\sqrt5 \approx 2.236, is separated by (9,7)(9, 7), which is far from both in xx. Neighbours in the yy order are not enough: the proposition allows up to seven points between, and the loop must go on while the yy distance is below δ\delta.

Exercise 21.6 ★★

This dichotomy computes a cube root with an absolute tolerance. Explain why it never ends for y=1015y = 10^{15}, 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
Listing 21.9. A dichotomy on reals code/bachelor-1/21-divide-and-conquer/listings/exo_float_bisect.py
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
Output 21.9. Three cube roots. Some lines are left out.
Solution

Solution of Exercise 21.6.

Near 10510^5, two consecutive doubles differ by 216−52=2−36≈1.5×10−112^{16 - 52} = 2^{-36} \approx 1.5 \times 10^{-11}, more than the tolerance. When lolo and hihi are consecutive doubles, their mean rounds to one of them, the loop assigns it, and nothing changes: the output shows mid=himid = hi. Repairs: stop when midmid equals lolo or hihi; or use a relative tolerance, hi−lo>10−12⋅hihi - lo > 10^{-12} \cdot hi; 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 O(nlog⁡n)O(n \log n), 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)
Largest slice sum code/bachelor-1/21-divide-and-conquer/exercises/max_subarray.py

A best slice lies in the left half, in the right half, or across the middle, where it is a best slice ending at mid−1mid - 1 followed by a best slice starting at midmid; both are found by one scan. So T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n). 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 O(nlog⁡n)O(n \log n).

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
Majority key code/bachelor-1/21-divide-and-conquer/exercises/majority.py

If a key cc held at most half of each half, it would hold at most ⌊mid/2⌋+⌊(n−mid)/2⌋≤n/2\lfloor mid/2 \rfloor + \lfloor (n - mid)/2 \rfloor \leq n/2 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 Θ(n)\Theta(n): T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n).

Exercise 21.9 ★★

Karatsuba’s method pads numbers of nn digits to the next power of 2. Show that it makes fewer than 3nlog⁡233 n^{\log_2 3} digit products, and that with a cutoff 2j2^j it makes 3k−j4j3^{k-j} 4^j on 2k2^k digits.

Solution

Solution of Exercise 21.9.

For numbers of dd digits, multiply takes the smallest power 2k≥d2^k \geq d, so 2k<2d2^k < 2d and 3k=(2k)log⁡23<(2d)log⁡23=3dlog⁡233^k = (2^k)^{\log_2 3} < (2d)^{\log_2 3} = 3 d^{\log_2 3}. With a cutoff 2j2^j, K(2k)=3K(2k−1)K(2^k) = 3K(2^{k-1}) for k>jk > j and K(2j)=4jK(2^j) = 4^j, the school method’s count: K(2k)=3k−j4jK(2^k) = 3^{k-j} 4^j.

Exercise 21.10 ★★★

Show that the median of medians with groups of three gives the recurrence T(n)≤T(n/3)+T(2n/3)+anT(n) \leq T(n/3) + T(2n/3) + an, and that this recurrence does not imply T(n)=O(n)T(n) = O(n): its solution with equality is Θ(nlog⁡n)\Theta(n \log n).

Solution

Solution of Exercise 21.10.

With groups of three, at least half of the n/3n/3 medians are at most the pivot, and each of their groups holds two keys at most the pivot: about n/3n/3 keys on each side, so the recursive call receives up to 2n/32n/3, and T(n)≤T(n/3)+T(2n/3)+anT(n) \leq T(n/3) + T(2n/3) + an. Now 1/3+2/3=11/3 + 2/3 = 1: no level of the recursion tree is smaller than the one above. Take T(n)=T(n/3)+T(2n/3)+anT(n) = T(n/3) + T(2n/3) + an and suppose T(j)≥ajlog⁡3jT(j) \geq a j \log_3 j for j<nj < n. Then

T(n)≥an3log⁡3n3+a2n3log⁡32n3+an=anlog⁡3n−an3−a2n3+a2n3log⁡32+an≥anlog⁡3n,T(n) \geq a\tfrac n3 \log_3 \tfrac n3 + a\tfrac{2n}{3} \log_3 \tfrac{2n}{3} + an = an \log_3 n - a\tfrac n3 - a\tfrac{2n}3 + a\tfrac{2n}3 \log_3 2 + an \geq an \log_3 n,

so T(n)=Ω(nlog⁡n)T(n) = \Omega(n \log n); with groups of three the method is not proved linear.

Exercise 21.11 ★★★

Buildings are rectangles (left,right,height)(\mathit{left}, \mathit{right}, \mathit{height}) standing on a line. Compute the skyline, the list of points where the visible height changes, by divide and conquer in O(nlog⁡n)O(n \log n).

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
The skyline code/bachelor-1/21-divide-and-conquer/exercises/skyline.py

Merging two outlines walks both lists once, keeping the current height of each, and records the larger one wherever it changes: Θ(n)\Theta(n) for outlines of O(n)O(n) points. Hence T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n). The test compares the outline’s height at every integer abscissa with the highest building standing there.

Exercise 21.12 ★★★

Find four positions i<j<k<mi < j < k < m of a list whose keys sum to a target in O(n2log⁡n)O(n^2 \log n), 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
Four keys with a given sum code/bachelor-1/21-divide-and-conquer/exercises/four_sum.py

The table keeps, for each sum of two keys, the pair (k,m)(k, m) with that sum and the largest kk. If a solution i<j<k<mi < j < k < m exists, then when the loops reach (i,j)(i, j), the sum a[k]+a[m]a[k] + a[m] is in the table with a pair whose first position is at least k>jk > j: a solution is returned. Conversely a returned quadruple has the target sum and increasing positions. The table takes Θ(n2)\Theta(n^2) steps, its sorting O(n2log⁡n)O(n^2 \log n), and the n(n−1)/2n(n - 1)/2 binary searches O(n2log⁡n)O(n^2 \log n). 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.

  1. How many digit products does the school method make for two numbers of nn digits? Check with the output.
  2. Show that a cell of r, before the carries, holds at most 81n81n.
  3. Show that propagating the carries once, at the end, costs Θ(n)\Theta(n) and gives the right digits.
  4. Why does the result of two nn-digit numbers fit in 2n2n digits?
  5. By what factor does the school method’s time grow when nn doubles, according to the table? What does the model predict?
  6. How many digit products does the opening’s multiplication of two 1000-digit numbers take?

Part II — Karatsuba’s identity.

  1. Expand abab with a=a110m+a0a = a_1 10^m + a_0, b=b110m+b0b = b_1 10^m + b_0.
  2. Prove a1b0+a0b1=a1b1+a0b0−(a1−a0)(b1−b0)a_1 b_0 + a_0 b_1 = a_1 b_1 + a_0 b_0 - (a_1 - a_0)(b_1 - b_0).
  3. Why do ∣a1−a0∣|a_1 - a_0| and ∣b1−b0∣|b_1 - b_0| have at most mm digits?
  4. What does difference return, and why does it compare from the top digit?
  5. The combine loop leaves cells that may be negative. Why does normalise still give the right digits?
  6. Write the recurrence for the number K(n)K(n) of digit products, nn a power of 2.

Part III — Exact counts.

  1. Prove K(2k)=3kK(2^k) = 3^k.
  2. Show that 3k=nlog⁡233^k = n^{\log_2 3} for n=2kn = 2^k.
  3. Compare K(1024)K(1024) with 102421024^2.
  4. Show that the other work of one call on nn digits is Θ(n)\Theta(n), and that the total work is still Θ(nlog⁡23)\Theta(n^{\log_2 3}).
  5. With a cutoff c=2jc = 2^j, how many digit products are made on 2k2^k digits (Exercise 21.9)? Give the count for n=1024n = 1024 and c=32c = 32.
  6. Which cutoff minimises the number of digit products? Why is a larger one used anyway?

Part IV — Where it pays, on this machine.

  1. Without a cutoff, by what factor is Karatsuba’s method slower than the school method at each nn of the table? How does that factor change when nn doubles?
  2. Estimate from that trend the size from which Karatsuba’s method without a cutoff would win.
  3. From which nn of the table does Karatsuba’s method with cutoff 8, then with cutoff 32, beat the school method?
  4. By what factor does the time with cutoff 32 grow when nn doubles at the end of the table? Compare with 33 and 44.
  5. CPython’s cutoff is 70 digits of 30 bits. How many decimal digits is that?
  6. State the named result, Karatsuba’s count.
Solution

Solution of Problem 21.1.

1. n2n^2, one for each pair of digits: 1 048 576 for n=1024n = 1024.

2. Cell tt receives the products aibja_i b_j with i+j=ti + j = t: at most one jj for each ii, so at most nn products, each at most 9×9=819 \times 9 = 81.

3. One pass over 2n2n cells, with a carry at most (81n+carry)/10<9n(81n + \mathit{carry})/10 < 9n: Θ(n)\Theta(n) steps on numbers of a few bytes. Each step replaces rt+carryr_t + \mathit{carry} by its last digit and carries the rest to cell t+1t + 1, which keeps ∑trt10t\sum_t r_t 10^t unchanged; at the end every cell is a digit.

4. a,b<10na, b < 10^n, so ab<102nab < 10^{2n}.

5. From 9412 to 39 270 to 167 668: by about 4.2 per doubling; the model predicts 4.

6. A million, 100021000^2; the program pads to 1024 digits and makes 1 048 576.

7. ab=a1b1102m+(a1b0+a0b1)10m+a0b0ab = a_1 b_1 10^{2m} + (a_1 b_0 + a_0 b_1) 10^m + a_0 b_0.

8. (a1−a0)(b1−b0)=a1b1−a1b0−a0b1+a0b0(a_1 - a_0)(b_1 - b_0) = a_1 b_1 - a_1 b_0 - a_0 b_1 + a_0 b_0; move the two middle terms to the other side.

9. 0≤a0,a1<10m0 \leq a_0, a_1 < 10^m, so ∣a1−a0∣<10m|a_1 - a_0| < 10^m.

10. The digits of ∣x−y∣|x - y|, as a list of the same length, and the sign of x−yx - y. Between two numbers of the same length, the first digit that differs from the top decides which is larger.

11. The loop makes ∑trt10t\sum_t r_t 10^t equal to the product. divmod writes any integer, negative or not, as 10q+d10q + d with 0≤d≤90 \leq d \leq 9, so each step keeps the sum and leaves a digit; the product is in [0,102n)[0, 10^{2n}), so the last carry is 0 and the cells are its digits.

12. K(1)=1K(1) = 1 and K(n)=3K(n/2)K(n) = 3K(n/2).

13. K(20)=1=30K(2^0) = 1 = 3^0, and K(2k+1)=3K(2k)=3⋅3k=3k+1K(2^{k+1}) = 3K(2^k) = 3 \cdot 3^k = 3^{k+1}.

14. 3k=2klog⁡23=(2k)log⁡23=nlog⁡233^k = 2^{k \log_2 3} = (2^k)^{\log_2 3} = n^{\log_2 3}.

15. 310=59 0493^{10} = 59\,049 against 1 048 576: about 18 times fewer.

16. The slices, the two differences, the combine loop and normalise each take Θ(n)\Theta(n) steps. So W(n)=3W(n/2)+Θ(n)W(n) = 3W(n/2) + \Theta(n), and since 3>213 > 2^1 the master theorem gives Θ(nlog⁡23)\Theta(n^{\log_2 3}): the leaves dominate, and the additions do not change the order.

17. 3k−j4j3^{k-j} 4^j; for n=1024n = 1024 and c=32c = 32, 35⋅45=248 8323^5 \cdot 4^5 = 248\,832.

18. The cutoff 1: each level handed to the school method multiplies the count by 4/34/3. 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 n=16n = 16 to 2048. The factor falls by about 0.7 per doubling at the end, close to the 3/43/4 expected when one time grows like 3k3^k and the other like 4k4^k.

20. With factors of about 1.4×0.75≈1.061.4 \times 0.75 \approx 1.06 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. 29 815/9772≈3.0529\,815 / 9772 \approx 3.05 and 9772/3204≈3.059772 / 3204 \approx 3.05: close to 3, where the school method grows by 4.

23. 70×30=210070 \times 30 = 2100 bits, and 2100log⁡102≈6322100 \log_{10} 2 \approx 632 decimal digits.

24. Karatsuba’s count: Karatsuba’s method multiplies two numbers of 2k2^k digits with exactly 3k3^k digit products, that is nlog⁡23≈n1.585n^{\log_2 3} \approx n^{1.585} for n=2kn = 2^k (questions 12 to 14), the counts printed by the program in Output 21.2; its whole cost is Θ(nlog⁡23)\Theta(n^{\log_2 3}) (question 16).

Istilah yang didefinisikan dalam bab ini

Lihat semua 1050 istilah di glosarium