কম্পিউটার বিজ্ঞান · বই 4 · স্নাতক দ্বিতীয় বর্ষ

University Computer Science — Year 2

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ

27Randomised Algorithms

The town keeps its 120 people in a list sorted by name. A quicksort that takes the first element as its pivot, given that list again, does the worst thing it can:

names = sorted(people())
n = len(names)
for label, data, pick in [
        ("first pivot, sorted list", names, first),
        ("first pivot, shuffled list", shuffle(names, random.Random(1)), first),
        ("random pivot, sorted list", names, random_pivot(random.Random(1)))]:
    count = [0]
    assert quicksort(data, pick, count) == names
    print(f"{label:27}: {count[0]:5} comparisons")
print(f"n(n - 1)/2 = {n * (n - 1) // 2}")
Listing 27.1. The sorted list of the town’s people, sorted again three ways code/bachelor-2/27-randomised-algorithms/listings/sorted_input.py
$ python sorted_input.py
first pivot, sorted list   :  7140 comparisons
first pivot, shuffled list :   856 comparisons
random pivot, sorted list  :   915 comparisons
n(n - 1)/2 = 7140
Output 27.1. A fixed pivot on sorted input makes every possible comparison; a shuffle first, or a random pivot, about one eighth of them.

With the first element as pivot, each call splits off one element and compares it with all the others: n(n−1)/2n(n-1)/2 comparisons, as the Year 1 volume counted. Sorted input is not rare, so a library cannot hope that its users avoid it. Choosing the pivot at random changes the question: there is no bad input any more, only unlucky coins, and the chapter shows they are rare. It then uses coins to make hash tables safe against an adversary, to store a set in a few bits per element, to test whether a 256-bit number is prime, and to find the weakest links of a network.

You already know

The mathematics Year 2 volume: random variables, expectation and its linearity, E[X+Y]=E[X]+E[Y]E[X + Y] = E[X] + E[Y] even when XX and YY are dependent; independent events; the geometric law, whose mean is 1/p1/p; Markov’s inequality, Pr⁡[X≥a]≤E[X]/a\Pr[X \geq a] \leq E[X]/a for X≥0X \geq 0. The Year 1 volume: quicksort and its average cost over random inputs; hash tables with chaining, and the promise that a good hash function keeps the chains short. The grade 9 volume: pseudo-random numbers, which a program draws from a seed and can draw again.

27.1 Las Vegas and Monte Carlo

Definition 27.1 (Randomised algorithm, Las Vegas, Monte Carlo)

A randomised algorithm may draw random numbers as it runs; its running time and its answer are then random variables, for each input. It is a Las Vegas algorithm if its answer is always correct and only its running time is random, and a Monte Carlo algorithm if its running time is bounded but its answer may be wrong with some probability.

Randomised quicksort is Las Vegas: the list always comes out sorted. A primality test that says “probably prime” is Monte Carlo. The listings draw their numbers from random.Random(seed): pseudo-random numbers, the same for the same seed, which is how every output of this chapter reruns identically. The analyses assume truly random draws.

Definition 27.2 (Expected running time)

The expected running time of a randomised algorithm on an input xx is the expectation, over its random draws, of its running time on xx. Its expected running time for size nn is the largest of these over the inputs of size nn.

This is not an average-case cost. An average over inputs assumes that inputs follow a law, and an adversary, or a user with a sorted list, can break it. The expected running time holds for every input: the randomness is in the algorithm, where nobody outside can choose it.

Definition 27.3 (One-sided error, amplification)

A Monte Carlo algorithm for a yes-or-no question has one-sided error if one of its answers is always right: for instance “composite” is always right and “prime” is wrong with probability at most ε\varepsilon. Amplification runs it kk times with independent draws and answers “prime” only if every run does.

Proposition 27.4 (Amplification)

If each run errs with probability at most ε\varepsilon, independently, the amplified algorithm is wrong with probability at most εk\varepsilon^k, and costs kk times as much.

Proof. It is wrong only if all kk runs are wrong, which by independence has probability at most εk\varepsilon^k. ∎

With ε=1/4\varepsilon = 1/4 and k=40k = 40, the error is at most 2−802^{-80}, far below the chance that the hardware errs during the run. A Monte Carlo algorithm whose answer can be checked cheaply becomes Las Vegas: run it until the check passes (Exercise 27.7).

27.2 Randomised quicksort and quickselect

def quicksort(a, pick, count):
    """Sort the list a of distinct keys; pick(a) chooses the pivot's index. Each element
    other than the pivot is compared with it once; count[0] adds them up."""
    if len(a) <= 1:
        return list(a)
    pivot = a[pick(a)]
    count[0] += len(a) - 1
    smaller = [x for x in a if x < pivot]
    larger = [x for x in a if x > pivot]
    return quicksort(smaller, pick, count) + [pivot] + quicksort(larger, pick, count)


def first(a):
    return 0


def random_pivot(rng):
    return lambda a: rng.randrange(len(a))


def shuffle(a, rng):
    """Fisher-Yates: position i receives a uniform choice among the positions >= i."""
    a = list(a)
    for i in range(len(a) - 1):
        j = rng.randrange(i, len(a))
        a[i], a[j] = a[j], a[i]
    return a
Listing 27.2. Quicksort with a pivot chosen by a function, and the Fisher–Yates shuffle code/bachelor-2/27-randomised-algorithms/listings/quicksort.py

Two ways remove the bad inputs: shuffle the list uniformly first, then use any fixed pivot rule; or choose each pivot uniformly at random. Both give the same law for the number of comparisons. The shuffle of the listing, due to Fisher and Yates, produces each of the n!n! orders with probability 1/n!1/n! (Exercise 27.11); the tempting version that swaps each position with any position is biased (Exercise 27.2).

One run of randomised quicksort on ten first names, printed by quicksort_trace.py. Each node is a pivot, with the number of names compared with it; its left subtree sorts the smaller names, its right subtree the larger ones. The run makes 9 + 1 + 6 + 4 + 1 + 1 = 22 comparisons. Two names are compared exactly when one of them is an ancestor of the other.
One run of randomised quicksort on ten first names, printed by quicksort_trace.py. Each node is a pivot, with the number of names compared with it; its left subtree sorts the smaller names, its right subtree the larger ones. The run makes 9+1+6+4+1+1=229 + 1 + 6 + 4 + 1 + 1 = 22 comparisons. Two names are compared exactly when one of them is an ancestor of the other.

The figure shows the key to the analysis. Number the keys z1<z2<⋯<znz_1 < z_2 < \dots < z_n in sorted order. Two keys are compared at most once, when one of them is the pivot, and never again since the pivot is then set aside.

Lemma 27.5 (Comparison probability)

In randomised quicksort, for i<ji < j, the keys ziz_i and zjz_j are compared with probability 2/(j−i+1)2/(j - i + 1).

Proof. Exercise 27.8: ziz_i and zjz_j stay in the same call until the first pivot drawn among zi,…,zjz_i, \dots, z_j, and they are compared if and only if that pivot is ziz_i or zjz_j. ∎

Theorem 27.6 (Randomised quicksort)

On every list of nn distinct keys, randomised quicksort makes on average exactly 2(n+1)Hn−4n2(n + 1)H_n - 4n comparisons, where Hn=1+1/2+⋯+1/nH_n = 1 + 1/2 + \dots + 1/n. This is about 2nln⁡n≈1.39 nlog⁡2n2n \ln n \approx 1.39\, n \log_2 n.

Proof. Let XijX_{ij} be 11 if ziz_i and zjz_j are compared and 00 otherwise. The number of comparisons is X=∑i<jXijX = \sum_{i < j} X_{ij}, and by linearity and Lemma 27.5,

E[X]=∑i<j2j−i+1=∑k=2n(n−k+1)2k,E[X] = \sum_{i < j} \frac{2}{j - i + 1} = \sum_{k = 2}^{n} (n - k + 1) \frac{2}{k},

grouping the pairs by k=j−i+1k = j - i + 1, of which there are n−k+1n - k + 1. This is 2(n+1)∑k=2n1k−2(n−1)=2(n+1)(Hn−1)−2n+2=2(n+1)Hn−4n2(n + 1)\sum_{k = 2}^{n} \frac{1}{k} - 2(n - 1) = 2(n + 1)(H_n - 1) - 2n + 2 = 2(n + 1)H_n - 4n. Finally Hn=ln⁡n+O(1)H_n = \ln n + O(1). ∎

$ python quicksort_rand.py
n = 120: mean 819.9 comparisons over 1,000 runs; 2(n+1)H_n - 4n = 819.3
smallest 669, largest 1156, worst case 7140
runs above 1.5 x 819.3: 0
Output 27.2. 1,000 runs on the sorted list of the town’s people, against the exact expectation.

The proof uses no independence between the XijX_{ij}, which are far from independent: linearity of expectation is the whole tool. The output shows more than the mean: in 1,000 runs, none passed one and a half times it, and the largest is a sixth of the worst case. Bounding the spread needs more than linearity; the chapter keeps to expectations.

The same idea finds the key of a given rank without sorting: partition around a random pivot, and continue only on the side that contains the rank.

def quickselect(a, k, rng, count):
    """The key of rank k (0 for the smallest) of the list a of distinct keys."""
    while True:
        pivot = a[rng.randrange(len(a))]
        count[0] += len(a) - 1
        smaller = [x for x in a if x < pivot]
        if k < len(smaller):
            a = smaller
        elif k == len(smaller):
            return pivot
        else:
            k -= len(smaller) + 1
            a = [x for x in a if x > pivot]
Listing 27.3. Quickselect: the key of rank kk with a random pivot code/bachelor-2/27-randomised-algorithms/listings/quickselect.py

Theorem 27.7 (Quickselect)

On every list of nn distinct keys and every rank, quickselect makes on average at most 4n4n comparisons.

Proof. Let T(n)T(n) be the largest expected number of comparisons over lists of size nn and ranks. The partition costs n−1n - 1; the pivot has rank ii with probability 1/n1/n, for 0≤i≤n−10 \leq i \leq n - 1, and the search continues on a side of size at most max⁡(i,n−1−i)\max(i, n - 1 - i). So T(n)≤n−1+1n∑i=0n−1T(max⁡(i,n−1−i))T(n) \leq n - 1 + \frac{1}{n} \sum_{i = 0}^{n - 1} T(\max(i, n - 1 - i)), and T(0)=T(1)=0T(0) = T(1) = 0. Assume T(k)≤4kT(k) \leq 4k for k<nk < n. The values max⁡(i,n−1−i)\max(i, n - 1 - i) run through the upper half of 0,…,n−10, \dots, n - 1 twice, and their sum is at most 3n2/43n^2/4 (check n=2rn = 2r and n=2r+1n = 2r + 1). Then T(n)≤n−1+4n⋅3n24=4n−1T(n) \leq n - 1 + \frac{4}{n} \cdot \frac{3n^2}{4} = 4n - 1. ∎

$ python quickselect.py
rank   0: mean  227.6 comparisons, largest 578; 4n = 480
rank  60: mean  373.5 comparisons, largest 758; 4n = 480
rank 119: mean  229.8 comparisons, largest 522; 4n = 480
Output 27.3. The smallest, the median and the largest name, 1,000 runs each.

The median is the most expensive rank, about 3.1 n3.1\,n here; the exact expectation for the median is close to 2(1+ln⁡2)n≈3.39 n2(1 + \ln 2) n \approx 3.39\, n for large nn, and 4n4n is a simple bound above it.

History

Tony Hoare published Quicksort in 1961, as an algorithm of a few lines in the journal of the computing society of the time.

27.3 Universal hashing

A hash table with a fixed function such as h(x)=x mod mh(x) = x \bmod m has bad inputs too: keys that are all multiples of mm all land in bucket 00. If the keys come from outside, from names typed in a form or from packets on a network, someone can send exactly those, and every lookup becomes a walk along a list of all the keys. The cure is the same as for quicksort: choose the function at random, after the keys are fixed.

Definition 27.8 (Universal family)

A set H\mathcal{H} of functions from the keys to {0,…,m−1}\{0, \dots, m - 1\} is a universal family if for any two distinct keys x≠yx \neq y, a function hh drawn uniformly from H\mathcal{H} makes them collide with probability at most 1/m1/m: Pr⁡[h(x)=h(y)]≤1/m\Pr[h(x) = h(y)] \leq 1/m.

Theorem 27.9 (Carter–Wegman)

Let pp be a prime larger than every key and m≥2m \geq 2. The functions ha,b(x)=((ax+b) mod p) mod mh_{a,b}(x) = ((ax + b) \bmod p) \bmod m, for 1≤a≤p−11 \leq a \leq p - 1 and 0≤b≤p−10 \leq b \leq p - 1, form a universal family.

Proof. Fix keys x≠yx \neq y in {0,…,p−1}\{0, \dots, p - 1\}, and let r=(ax+b) mod pr = (ax + b) \bmod p, s=(ay+b) mod ps = (ay + b) \bmod p. Then r−s≡a(x−y)(modp)r - s \equiv a(x - y) \pmod p, and since pp is prime and neither aa nor x−yx - y is a multiple of pp, r≠sr \neq s. Conversely, given r≠sr \neq s, the equations determine a=(r−s)(x−y)−1 mod pa = (r - s)(x - y)^{-1} \bmod p, which is not 00, and then b=(r−ax) mod pb = (r - ax) \bmod p: the map (a,b)↦(r,s)(a, b) \mapsto (r, s) is a bijection from the p(p−1)p(p - 1) functions onto the pairs r≠sr \neq s. Drawing (a,b)(a, b) uniformly therefore draws (r,s)(r, s) uniformly among the pairs of distinct values. The keys collide when r≡s(modm)r \equiv s \pmod m. For each rr, the values s≠rs \neq r in {0,…,p−1}\{0, \dots, p - 1\} with s≡r(modm)s \equiv r \pmod m number at most ⌈p/m⌉−1≤(p−1)/m\lceil p/m \rceil - 1 \leq (p - 1)/m. So the colliding pairs number at most p(p−1)/mp(p - 1)/m, out of p(p−1)p(p - 1). ∎

The modular inverse used in the proof exists because pp is prime, the property the mathematics books prove with Bézout’s identity; the program never computes it.

Corollary 27.10 (Short chains)

Store nn keys in a table of mm buckets with chaining, with a function drawn from a universal family. For every key xx of the table, the expected length of its chain is at most 1+(n−1)/m<1+α1 + (n - 1)/m < 1 + \alpha, where α=n/m\alpha = n/m. For a key not in the table, the expected length of the chain it lands in is at most α\alpha.

Proof. The chain of xx holds xx and the keys y≠xy \neq x with h(y)=h(x)h(y) = h(x). Its length is 1+∑y≠xCy1 + \sum_{y \neq x} C_y, where CyC_y is 11 on a collision, and E[Cy]≤1/mE[C_y] \leq 1/m. By linearity, the expectation is at most 1+(n−1)/m1 + (n - 1)/m. For a key not in the table, the same sum has nn terms and no 11. ∎

This is the promise the Year 1 volume made for hash tables, now kept for every set of keys, with the randomness in the choice of the function. The listing attacks both kinds of function with keys that are all multiples of mm.

P = 2**31 - 1  # a prime larger than every key


def draw(m, rng):
    """A random member of the family h(x) = ((a x + b) mod p) mod m."""
    a, b = rng.randrange(1, P), rng.randrange(P)
    return lambda x: (a * x + b) % P % m


def chains(keys, h, m):
    lengths = [0] * m
    for x in keys:
        lengths[h(x)] += 1
    return lengths
Listing 27.4. A function drawn from the Carter–Wegman family, and the chain lengths it gives code/bachelor-2/27-randomised-algorithms/listings/universal_hash.py
$ python universal_hash.py
    n  fixed: longest | universal, 1,000 draws: longest (median)  key's chain  bound
  200            200 |                                     5         1.991  1.995
  400            400 |                                     5         2.000  1.998
  600            600 |                                     5         1.998  1.998
  800            800 |                                     5         1.999  1.999
 1000           1000 |                                     5         1.999  1.999
Output 27.4. Keys that are all multiples of mm: one chain of nn keys for x mod mx \bmod m; for a random member of the family, the median longest chain over 1,000 draws, and the average chain length seen by a key, against the bound.
The longest chain under the attack of , on a logarithmic scale: all n keys in one chain for the fixed function, five for a function drawn after the keys.
The longest chain under the attack of Output 27.4, on a logarithmic scale: all nn keys in one chain for the fixed function, five for a function drawn after the keys.

The measured average chain of a key matches the bound 1+(n−1)/m1 + (n - 1)/m to within the noise of 1,000 draws: for these keys the bound is reached. The adversary has not disappeared: once a function is drawn, keys exist that collide under it. A server must therefore keep its draw secret, and libraries of several languages draw a secret seed for their string hashing when the program starts.

History

Lawrence Carter and Mark Wegman defined universal classes of hash functions in 1979, with the family of Theorem 27.9 among their examples.

27.4 Bloom filters

A set of a million long strings takes megabytes as a hash table. Often one only needs to answer “certainly not in the set” quickly, and to look further for the rest: a browser checking addresses against a list of known bad sites, a database checking whether a disk block might hold a key before reading it.

Definition 27.11 (Bloom filter, false positive)

A Bloom filter is an array of mm bits, all 00 at first, and kk hash functions h1,…,hkh_1, \dots, h_k with values in {0,…,m−1}\{0, \dots, m - 1\}. Adding a key xx sets the bits h1(x),…,hk(x)h_1(x), \dots, h_k(x) to 11. A lookup of yy answers “present” if its kk bits are all 11. A false positive is a lookup that answers “present” for a key that was never added.

A key that was added always finds its bits set: there are no false negatives. Keys cannot be removed, since a bit may be shared.

class Bloom:
    def __init__(self, m, k, rng):
        self.bits = bytearray(m)
        self.hashes = [draw(m, rng) for _ in range(k)]

    def add(self, x):
        for h in self.hashes:
            self.bits[h(x)] = 1

    def __contains__(self, x):  # never wrong for a key added; sometimes for others
        return all(self.bits[h(x)] for h in self.hashes)
Listing 27.5. A Bloom filter whose kk functions are drawn independently from the universal family code/bachelor-2/27-randomised-algorithms/listings/bloom.py
$ python bloom_small.py
add Ada: bits [15, 5, 11]
add Ben: bits [8, 10, 6]
add Cy : bits [9, 6, 11]
filter: 0000011011110001
36 other first names looked up: 3 false positives
   Aarav: bits [14, 15, 9], in filter: False
   Hana: bits [10, 11, 6], in filter: True
Output 27.5. Three names in 16 bits with 3 functions, and the other first names of the town looked up.
The filter of . Each added name sets 3 bits; the bits 6 and 11 are shared. Hana was never added, but her bits 10, 11 and 6 were all set by Ben and Cy: a false positive.
The filter of Output 27.5. Each added name sets 3 bits; the bits 6 and 11 are shared. Hana was never added, but her bits 10, 11 and 6 were all set by Ben and Cy: a false positive.

Proposition 27.12 (False-positive rate)

Assume that the knkn hash values of nn added keys, and the kk values of a key looked up, are independent and uniform on {0,…,m−1}\{0, \dots, m - 1\}. After nn keys, a given bit is still 00 with probability (1−1/m)kn≈e−kn/m(1 - 1/m)^{kn} \approx e^{-kn/m}, and if the bits are treated as independent, a key not added is a false positive with probability about

(1−e−kn/m)k.\left(1 - e^{-kn/m}\right)^k .

For a given ratio m/nm/n this is smallest for k=(m/n)ln⁡2k = (m/n) \ln 2, where it is 2−k≈0.6185m/n2^{-k} \approx 0.6185^{m/n}.

Proof. Each of the knkn values misses a given bit with probability 1−1/m1 - 1/m, independently; and (1−1/m)kn=eknln⁡(1−1/m)≈e−kn/m(1 - 1/m)^{kn} = e^{kn \ln(1 - 1/m)} \approx e^{-kn/m} for large mm. A key not added is a false positive when its kk bits are 11; treating them as independent gives the formula. Write q=e−kn/mq = e^{-kn/m}, so that k=−(m/n)ln⁡qk = -(m/n) \ln q and the logarithm of the rate is kln⁡(1−q)=−(m/n)ln⁡qln⁡(1−q)k \ln(1 - q) = -(m/n) \ln q \ln(1 - q). The product ln⁡qln⁡(1−q)\ln q \ln(1 - q) is symmetric in qq and 1−q1 - q, and largest at q=1/2q = 1/2, which minimises the rate: then k=(m/n)ln⁡2k = (m/n) \ln 2 and the rate is (1/2)k=2−(m/n)ln⁡2≈0.6185m/n(1/2)^k = 2^{-(m/n)\ln 2} \approx 0.6185^{m/n}. ∎

The independence of the bits is an approximation; the measurement shows it is a good one. With 8 bits per key the best rate is about 2%2\%, with 10 bits about 0.8%0.8\%, whatever the length of the keys.

$ python bloom.py
n = 1000 keys, m = 8000 bits; 100,000 other keys queried
 k  measured  (1 - e^(-kn/m))^k
 1    0.1177    0.1175
 2    0.0486    0.0489
 3    0.0300    0.0306
 4    0.0241    0.0240
 5    0.0223    0.0217
 6    0.0214    0.0216
 7    0.0241    0.0229
 8    0.0246    0.0255
 9    0.0280    0.0292
10    0.0321    0.0342
best k = (m/n) ln 2 = 5.55
Output 27.6. 1,000 keys in 8,000 bits, measured with 100,000 other keys for each kk.
The false-positive rate of  against the formula of , for m/n = 8. Too few functions leave each lookup a weak test; too many fill the array with ones. The minimum is near k = 8 2 5.5.
The false-positive rate of Output 27.6 against the formula of Proposition 27.12, for m/n=8m/n = 8. Too few functions leave each lookup a weak test; too many fill the array with ones. The minimum is near k=8ln⁡2≈5.5k = 8 \ln 2 \approx 5.5.

In practice

Burton Bloom described the structure in 1970, for a dictionary too large for memory. Storage engines that keep sorted files of keys on disk put a Bloom filter in front of each file, so that most lookups of absent keys never read the file.

27.5 Primality

Public-key cryptography needs random primes of hundreds of bits. Trial division up to n\sqrt{n} takes about 21282^{128} steps for a 256-bit number. A randomised test takes a few modular exponentiations, each O(log⁡n)O(\log n) multiplications by repeated squaring.

Definition 27.13 (Fermat witness, Carmichael number)

Let n>2n > 2 be odd and 1≤a≤n−11 \leq a \leq n - 1. If an−1≢1(modn)a^{n-1} \not\equiv 1 \pmod n, then aa is a Fermat witness for nn; otherwise nn passes for the base aa. A Carmichael number is an odd composite number that passes for every base coprime to it.

Proposition 27.14 (The Fermat test)

If nn is prime, it passes for every base. If nn is composite and has at least one Fermat witness coprime to it, then at least half of the bases coprime to nn are Fermat witnesses.

Proof. The first part is Fermat’s little theorem, from the mathematics books. For the second, let aa be a witness coprime to nn and b1,…,brb_1, \dots, b_r the bases coprime to nn for which nn passes. The products abi mod nab_i \bmod n are coprime to nn and distinct, since aa is invertible modulo nn. Each is a witness: (abi)n−1=an−1bin−1≡an−1≢1(ab_i)^{n-1} = a^{n-1} b_i^{n-1} \equiv a^{n-1} \not\equiv 1. So there are at least as many witnesses as passing bases. ∎

The Carmichael numbers escape the second part, and they exist: 561=3⋅11⋅17561 = 3 \cdot 11 \cdot 17 is the smallest. A sharper test asks more of a prime.

Definition 27.15 (Miller–Rabin witness)

Let n>2n > 2 be odd, and write n−1=2sdn - 1 = 2^s d with dd odd. A base aa is a Miller–Rabin witness for nn if ad≢1a^d \not\equiv 1 and a2id≢−1(modn)a^{2^i d} \not\equiv -1 \pmod n for every 0≤i<s0 \leq i < s.

A prime pp has no Miller–Rabin witness. The sequence ad,a2d,…,a2sd=ap−1a^d, a^{2d}, \dots, a^{2^s d} = a^{p-1} ends with 11, by Fermat, and each term is the square of the one before. If x2≡1(modp)x^2 \equiv 1 \pmod p, then pp divides (x−1)(x+1)(x - 1)(x + 1), so x≡±1x \equiv \pm 1: the term before the first 11, if there is one, is −1-1.

def miller_rabin_passes(n, a):
    """Write n - 1 = 2^s d with d odd. A prime n passes for every base: either
    a^d = 1, or one of a^d, a^(2d), ..., a^(2^(s-1) d) is -1 mod n."""
    s, d = 0, n - 1
    while d % 2 == 0:
        s, d = s + 1, d // 2
    x = pow(a, d, n)
    if x in (1, n - 1):
        return True
    for _ in range(s - 1):
        x = x * x % n
        if x == n - 1:
            return True
    return False  # a is a witness: n is composite


def is_probable_prime(n, rounds, rng):
    """Monte Carlo: 'composite' is always right; 'prime' is wrong with probability
    at most 4^-rounds."""
    if n < 4:
        return n in (2, 3)
    if n % 2 == 0:
        return False
    return all(miller_rabin_passes(n, rng.randrange(2, n - 1)) for _ in range(rounds))
Listing 27.6. The Miller–Rabin test for one base, and the amplified Monte Carlo test code/bachelor-2/27-randomised-algorithms/listings/primality.py

Theorem 27.16 (Miller–Rabin)

If n>4n > 4 is odd and composite, at most a quarter of the bases 1≤a≤n−11 \leq a \leq n - 1 are not Miller–Rabin witnesses. So kk rounds with independent uniform bases answer “prime” for a composite number with probability at most 4−k4^{-k}.

Proof. Admitted at this level. ∎

The proof uses the structure of the group of units modulo nn and the Chinese remainder theorem, which the mathematics books develop. The second sentence follows by Proposition 27.4.

$ python fermat_mr.py
n =  561: Fermat passes  318 of  318 coprime bases; Miller-Rabin passes    8 of 558 bases
n = 1105: Fermat passes  766 of  766 coprime bases; Miller-Rabin passes   28 of 1102 bases
n = 1729: Fermat passes 1294 of 1294 coprime bases; Miller-Rabin passes  160 of 1726 bases
n = 1009: Fermat passes 1006 of 1006 coprime bases; Miller-Rabin passes 1006 of 1006 bases
Output 27.7. Three Carmichael numbers and a prime, every base tried.

The three Carmichael numbers pass the Fermat test for all their coprime bases, and the Miller–Rabin test catches them with more than 90%90\% of the bases. To draw a random prime of 256 bits, draw random odd numbers of 256 bits until one passes. By the prime number theorem, a number near NN is prime with probability about 1/ln⁡N1/\ln N, an odd one about 2/ln⁡N2/\ln N; the number of draws follows a geometric law of mean about ln⁡N/2\ln N / 2.

$ python random_prime.py
last prime found: f231cb4067aef03fb1b912948cdfa2fcf29aa45fdf...
mean trials over 200 primes: 94.7; (ln 2^256) / 2 = 88.7
fewest 1, most 512
Output 27.8. 200 random primes of 256 bits: the number of odd numbers tried for each.

The mean, 94.7, is within the noise of 200 draws of the model’s ln⁡(2256)/2≈88.7\ln(2^{256})/2 \approx 88.7: a geometric law of mean 88 has a standard deviation near 88, so the mean of 200 draws varies by about 88/200≈688/\sqrt{200} \approx 6. The largest, 512, shows how long the tail of a geometric law is.

History

Gary Miller published in 1976 a test that is correct if a form of the Riemann hypothesis holds; Michael Rabin made it probabilistic, with a proven error bound and no hypothesis, in a paper published in 1980.

27.6 Random choices that approximate

Satisfying many clauses. Some problems are hard to solve exactly but easy to solve well by tossing coins. In the satisfiability problem of Chapter 24, a formula is a conjunction of clauses, and one may ask for an assignment that satisfies as many clauses as possible.

Proposition 27.17 (A random assignment)

Give each variable the value true or false with probability 1/21/2, independently. A clause of kk literals on distinct variables is satisfied with probability 1−2−k1 - 2^{-k}. So the expected number of satisfied clauses is at least half of them, and at least three quarters if every clause has two literals or more.

Proof. The clause is false only if each of its kk literals is false, which happens with probability 2−k2^{-k} since the variables are distinct and independent. Summing over the clauses with linearity gives the expected number, and 1−2−k≥1/21 - 2^{-k} \geq 1/2, or ≥3/4\geq 3/4 when k≥2k \geq 2. ∎

$ python maxsat.py
200 clauses: mean satisfied  149.7, expected  150.0, best of 1,000 runs 169
200 clauses: mean satisfied  152.5, expected  152.5, best of 1,000 runs 168
Output 27.9. Random assignments on 200 clauses of two literals, then on a mix of one, two and three.

An expectation is reached by some outcome: an assignment satisfying at least three quarters of the 2-literal clauses always exists, which the proposition proves without exhibiting one.

Karger’s minimum cut. A cut of an undirected graph splits its vertices into two non-empty parts; its size is the number of edges between them. Unlike the cuts of Chapter 26, no source or sink is fixed: the question is the smallest cut of all.

Definition 27.18 (Edge contraction)

In a multigraph (a graph that may have several edges between two vertices), contracting an edge {u,v}\{u, v\} replaces uu and vv by a single vertex, keeps every other edge of uu or vv with its end moved to the new vertex, and removes the edges between uu and vv, which would become loops.

Karger’s algorithm contracts a uniformly random edge until two vertices remain, and returns the edges between them. Each vertex then stands for a set of original vertices, and the edges between the two are a cut of the original graph.

def contract(vertices, edges, rng, log=None):
    """Contract random edges until two super-vertices remain. Taking the edges in a
    random order and skipping those inside a super-vertex picks each contraction
    uniformly among the edges left. Returns the cut: the edges between the two."""
    parent = {v: v for v in vertices}
    left = len(vertices)
    order = list(edges)
    rng.shuffle(order)
    for u, v in order:
        if left == 2:
            break
        ru, rv = find(parent, u), find(parent, v)
        if ru != rv:  # an edge inside a super-vertex would be a self-loop
            parent[ru] = rv
            left -= 1
            if log is not None:
                log.append((u, v))
    side = {v for v in vertices if find(parent, v) == find(parent, vertices[0])}
    return [(u, v) for u, v in edges if (u in side) != (v in side)], side


def karger(vertices, edges, runs, rng):
    """The smallest cut found in independent runs."""
    return min((contract(vertices, edges, rng) for _ in range(runs)),
               key=lambda r: len(r[0]))
Listing 27.7. Karger’s algorithm: the contractions as unions, the edges taken in a random order code/bachelor-2/27-randomised-algorithms/listings/karger.py

The listing does not build the multigraph. It takes the edges in a random order and contracts each one unless its ends are already merged. An edge whose ends are merged is exactly a loop, so the first edge of the order that is not a loop is uniform among the edges that remain: the same law as the algorithm.

$ python karger_demo.py
contracted: bd cd eh ac gh fh
cut of 2 edges: de cf | one side: abcd
minimum cut found in 2147 of 10,000 runs; bound 2/(n(n-1)) = 0.0357
Output 27.10. Two groups of four friends joined by two friendships: one run, and the success rate.
The run of . The three contractions bd, cd, eh leave five vertices and a multigraph (three edges between a and bcd); three more leave two, joined by the two red edges, the minimum cut. A run fails as soon as it contracts a red edge.
The run of Output 27.10. The three contractions bdbd, cdcd, eheh leave five vertices and a multigraph (three edges between aa and bcdbcd); three more leave two, joined by the two red edges, the minimum cut. A run fails as soon as it contracts a red edge.

Theorem 27.19 (Karger)

Let CC be a minimum cut of a connected multigraph with n≥2n \geq 2 vertices. One run of the contraction algorithm returns exactly CC with probability at least 2/(n(n−1))2/(n(n - 1)). With n(n−1)2ln⁡1δ\frac{n(n - 1)}{2} \ln \frac{1}{\delta} independent runs, keeping the smallest cut found, it misses every minimum cut with probability at most δ\delta.

Proof. Let c=∣C∣c = |C|. The run returns CC if it never contracts an edge of CC: then the two final vertices are the two sides of CC. Every vertex of the multigraph has degree at least cc at every stage, since the edges at a vertex form a cut of the original graph (its set of original vertices against the rest). With rr vertices left there are therefore at least rc/2rc/2 edges, and a uniform edge is in CC with probability at most c/(rc/2)=2/rc/(rc/2) = 2/r, if no edge of CC was contracted yet. The stages have r=n,n−1,…,3r = n, n - 1, \dots, 3 vertices, so the run avoids CC with probability at least

∏r=3n(1−2r)=∏r=3nr−2r=1⋅2(n−1)n,\prod_{r = 3}^{n} \left(1 - \frac{2}{r}\right) = \prod_{r = 3}^{n} \frac{r - 2}{r} = \frac{1 \cdot 2}{(n - 1) n},

the product telescoping. With NN independent runs, all of them miss CC with probability at most (1−2/(n(n−1)))N≤e−2N/(n(n−1))(1 - 2/(n(n - 1)))^N \leq e^{-2N/(n(n - 1))}, using 1−x≤e−x1 - x \leq e^{-x}; this is δ\delta for the NN of the statement. ∎

The bound is for one given minimum cut, in the worst graph. The measured success in Output 27.10, about 21%21\%, is six times the bound 3.6%3.6\%. A run is a near-linear pass over the edges, and O(n2log⁡n)O(n^2 \log n) runs give a total far above the cost of the best methods, but the algorithm is three lines and its analysis one product.

History

David Karger published the contraction algorithm in 1993.

27.7 Exercises

Exercise 27.1 ★

1729=7⋅13⋅191729 = 7 \cdot 13 \cdot 19 passes the Miller–Rabin test for 160 of the 1,726 bases from 22 to 17271727 (Output 27.7). What does the kk-round test of Listing 27.6 answer for 1729, and with which probabilities, for k=1,2,3,5k = 1, 2, 3, 5? Compare with exo_monte_carlo.py.

Solution

Solution of Exercise 27.1.

Each round draws a base uniformly in 2,…,17272, \dots, 1727 and 1729 passes with probability q=160/1726≈0.0927q = 160/1726 \approx 0.0927. The test answers “composite” unless all kk rounds pass, so it answers “prime”, wrongly, with probability qkq^k: about 9.3%9.3\%, 0.86%0.86\%, 0.080%0.080\% and 0.0007%0.0007\% for k=1,2,3,5k = 1, 2, 3, 5. “Composite” is always right.

$ python exo_monte_carlo.py
k = 1: 'prime' in   9414 of 100,000 runs; (0.0927)^k x 100,000 =   9270.0
k = 2: 'prime' in    912 of 100,000 runs; (0.0927)^k x 100,000 =    859.3
k = 3: 'prime' in     86 of 100,000 runs; (0.0927)^k x 100,000 =     79.7
k = 5: 'prime' in      1 of 100,000 runs; (0.0927)^k x 100,000 =      0.7
Output 27.12. The wrong answers counted over 100,000 runs.

Exercise 27.2 ★

A shuffle swaps each position ii with a position drawn uniformly among all nn. For n=3n = 3, count the 333^3 sequences of choices that produce each order, and explain from the numbers 2727 and 66 why no such shuffle can be uniform. Check with exo_shuffle.py.

Solution

Solution of Exercise 27.2.

$ python exo_shuffle.py
swap with any position: 27 choices; 012:4 021:5 102:5 120:5 201:4 210:4
Fisher-Yates          :  6 choices; 012:1 021:1 102:1 120:1 201:1 210:1
Output 27.13. Every sequence of choices of the two shuffles for n=3n = 3.

The 27 equally likely sequences give the orders 012012, 201201, 210210 four times each and the three others five times. No shuffle that makes nn uniform choices among nn can be uniform for n=3n = 3: each order would need 27/627/6 sequences, which is not a whole number. Fisher–Yates makes 3⋅2⋅1=63 \cdot 2 \cdot 1 = 6 choices, one per order.

Exercise 27.3 ★

Write a function that reads a stream of unknown length once and returns kk of its items, each set of kk items being equally likely, keeping only kk items in memory. Check it exhaustively for n=6n = 6 and k=2k = 2.

Solution

Solution of Exercise 27.3.

def reservoir(stream, k, choose):
    """Keep the first k items; item i (from 0) then replaces a random kept item with
    probability k/(i + 1). choose(i) returns a uniform number in 0..i."""
    sample = []
    for i, x in enumerate(stream):
        if i < k:
            sample.append(x)
        else:
            j = choose(i)
            if j < k:
                sample[j] = x
    return sample
Reservoir sampling code/bachelor-2/27-randomised-algorithms/listings/exo_reservoir.py
$ python exo_reservoir.py
360 choice sequences, 15 samples of 2 out of 6, each obtained {24} times
5 lines out of 10,000: ['loan 7149', 'loan 3669', 'loan 4689', 'loan 6152', 'loan 7994']
Output 27.14. All 3⋅4⋅5⋅63 \cdot 4 \cdot 5 \cdot 6 sequences of choices for n=6n = 6, k=2k = 2.

By induction on i≥ki \geq k: after the items 0,…,i−10, \dots, i - 1, every set of kk of them is the sample with probability 1/(ik)1/\binom{i}{k}. Item ii enters with probability k/(i+1)k/(i + 1), replacing a uniform one of the kk. A set SS of kk items among 0,…,i0, \dots, i that does not contain ii is the new sample if it was the old one and ii did not enter: 1(ik)⋅i+1−ki+1=1(i+1k)\frac{1}{\binom{i}{k}} \cdot \frac{i + 1 - k}{i + 1} = \frac{1}{\binom{i + 1}{k}}. A set SS containing ii is the new sample if the old one was S∖{i}S \setminus \{i\} plus one of the i−k+1i - k + 1 other items, ii entered, and replaced that item: (i−k+1)⋅1(ik)⋅1i+1=1(i+1k)(i - k + 1) \cdot \frac{1}{\binom{i}{k}} \cdot \frac{1}{i + 1} = \frac{1}{\binom{i + 1}{k}}.

Exercise 27.4 ★

A trial succeeds with probability pp, independently of the others. Prove that the expected number of trials up to the first success is 1/p1/p. Deduce the expected number of odd 256-bit numbers drawn in Output 27.8, taking the probability that one is prime to be 2/ln⁡22562/\ln 2^{256}.

Solution

Solution of Exercise 27.4.

Let EE be the expectation. The first trial succeeds with probability pp; otherwise one trial is spent and the process starts again: E=1+(1−p)EE = 1 + (1 - p)E, so E=1/pE = 1/p (the sum ∑t≥1tp(1−p)t−1\sum_{t \geq 1} t p (1 - p)^{t - 1} gives the same). With p=2/ln⁡2256p = 2/\ln 2^{256}, E=256ln⁡2/2≈88.7E = 256 \ln 2 / 2 \approx 88.7; Output 27.8 measured 94.794.7, one standard error of the mean of 200 draws (1−p/p≈88\sqrt{1 - p}/p \approx 88 divided by 200\sqrt{200}, about 6) above it: sampling noise.

Exercise 27.5 ★★

341=11⋅31341 = 11 \cdot 31. Show that 2340≡1(mod341)2^{340} \equiv 1 \pmod{341} (210=1024=3⋅341+12^{10} = 1024 = 3 \cdot 341 + 1), so that base 2 does not reveal 341, but base 3 does. Count the bases that do not reveal it, and show that Miller–Rabin with base 2 does. Check with exo_341.py.

Solution

Solution of Exercise 27.5.

210≡1(mod341)2^{10} \equiv 1 \pmod{341}, so 2340=(210)34≡12^{340} = (2^{10})^{34} \equiv 1: base 2 passes. Base 3 does not.

$ python exo_341.py
298 coprime bases in 2..339; Fermat liars: 98, the first ones [2, 4, 8, 15, 16, 23, 27, 29]
2^340 mod 341 = 1; 3^340 mod 341 = 56
2^85 mod 341 = 32, 2^170 mod 341 = 1; Miller-Rabin with base 2 passes: False
Output 27.15. The Fermat liars of 341, and base 2 in Miller–Rabin.

98 of the 298 bases coprime to 341 pass, fewer than half, as Proposition 27.14 requires. For Miller–Rabin, 340=22⋅85340 = 2^2 \cdot 85: 285≡322^{85} \equiv 32, not ±1\pm 1, and 2170≡12^{170} \equiv 1, not −1-1, so 2 is a witness. The square root 3232 of 11 that is neither 11 nor −1-1 proves 341 composite: 341341 divides (32−1)(32+1)(32 - 1)(32 + 1) without dividing either factor, and indeed 3131 and 1111 are its factors.

Exercise 27.6 ★★

A Bloom filter takes its kk positions as h(x),h(x)+1,…,h(x)+k−1 mod mh(x), h(x) + 1, \dots, h(x) + k - 1 \bmod m from a single function hh, to save time. Compare its false-positive rate with the filter of Listing 27.5 using exo_bloom_bug.py, and explain the difference.

Solution

Solution of Exercise 27.6.

$ python exo_bloom_bug.py
Bloom       k = 6: 4216 bits set, false positives 0.0216
Consecutive k = 6: 4289 bits set, false positives 0.2548
Output 27.16. Consecutive positions against independent functions, n=1000n = 1000, m=8000m = 8000, k=6k = 6.

Both set about the same number of bits, but the consecutive version sets them in runs of six. A key not added is rejected only if one of its six bits is 00; its bits are consecutive too, and inside a run, or across two runs that touch, they are all 11. The six tests are no longer independent: once h(y)h(y) falls in a run, the next bits are very likely set. The rate, 25%25\%, is closer to that of a single test than to (1−e−kn/m)k(1 - e^{-kn/m})^k.

Exercise 27.7 ★★

Modulo a prime pp, half the numbers 1,…,p−11, \dots, p - 1 are not squares, and Euler’s criterion recognises them: a(p−1)/2≡−1a^{(p - 1)/2} \equiv -1. Write a Monte Carlo algorithm that returns a non-square after at most kk draws and is wrong with probability 2−k2^{-k}, then a Las Vegas one that is never wrong. What is its expected number of draws?

Solution

Solution of Exercise 27.7.

$ python exo_las_vegas.py
Monte Carlo, k =  1: wrong in 5056 of 10,000 runs; 10,000 x 2^-k = 5000.0
Monte Carlo, k =  3: wrong in 1296 of 10,000 runs; 10,000 x 2^-k = 1250.0
Monte Carlo, k = 10: wrong in    5 of 10,000 runs; 10,000 x 2^-k = 9.8
Las Vegas: always right; mean draws 2.028, most 14
Output 27.17. The Monte Carlo version for three values of kk, and the Las Vegas version.

Each draw is a non-square with probability 1/21/2, independently. The Monte Carlo version stops at the first draw that passes the check, or after kk draws, and is wrong only if all kk fail: probability 2−k2^{-k}. The Las Vegas version draws until the check passes; its number of draws follows a geometric law of mean 1/(1/2)=21/(1/2) = 2 (Exercise 27.4), and the measured mean is 2.032.03.

Exercise 27.8 ★★

Prove Lemma 27.5.

Solution

Solution of Exercise 27.8.

Let Z={zi,…,zj}Z = \{z_i, \dots, z_j\}, of j−i+1j - i + 1 keys. As long as no pivot has been drawn from ZZ, the whole of ZZ stays in one call: a pivot smaller than ziz_i or larger than zjz_j sends all of ZZ to the same side. Consider the first pivot drawn from ZZ. It is drawn uniformly from the list of the call, which contains ZZ, so given that it falls in ZZ it is uniform on ZZ. If it is ziz_i or zjz_j, it is compared with every key of the call, the other one among them. Otherwise it lies strictly between them, sends ziz_i to the left and zjz_j to the right, and they are never in the same call again. So they are compared with probability 2/(j−i+1)2/(j - i + 1).

Exercise 27.9 ★★

On the graph of Output 27.10, run Karger’s algorithm rr times and keep the smallest cut, for r=1,2,5,10,20r = 1, 2, 5, 10, 20, and measure how often it is the minimum cut. Compare with 1−(1−p)r1 - (1 - p)^r for the measured pp and for the bound.

Solution

Solution of Exercise 27.9.

$ python exo_karger_rep.py
  r  success  1-(1-p)^r  1-(1-2/(n(n-1)))^r
  1    0.216      0.215               0.036
  2    0.383      0.383               0.070
  5    0.701      0.701               0.166
 10    0.918      0.911               0.305
 20    0.995      0.992               0.517
Output 27.18. The best of rr runs, 2,000 trials each.

With independent runs, the best of rr is the minimum cut unless every run misses it: 1−(1−p)r1 - (1 - p)^r. The measured values follow this law with the measured p=0.2147p = 0.2147. The bound, p≥2/56p \geq 2/56, predicts much less: it promises 99%99\% only after about 562ln⁡100≈129\frac{56}{2} \ln 100 \approx 129 runs, where 20 are enough on this graph.

Exercise 27.10 ★★★

Store nn keys in m=nm = n buckets with a function drawn from a universal family, and let LL be the longest chain. Show that L(L−1)≤∑jcj(cj−1)L(L - 1) \leq \sum_j c_j(c_j - 1), where cjc_j is the length of chain jj, that the expectation of this sum is at most n(n−1)/mn(n - 1)/m, and deduce E[L]≤1+nE[L] \leq 1 + \sqrt{n}. Why does Output 27.4 show far less?

Solution

Solution of Exercise 27.10.

The longest chain jj contributes L(L−1)L(L - 1) to the sum, and the other terms are non-negative. The sum ∑jcj(cj−1)\sum_j c_j(c_j - 1) counts the ordered pairs of distinct keys in the same bucket, so its expectation is ∑x≠yPr⁡[h(x)=h(y)]≤n(n−1)/m=n−1\sum_{x \neq y} \Pr[h(x) = h(y)] \leq n(n - 1)/m = n - 1. Since (L−1)2≤L(L−1)(L - 1)^2 \leq L(L - 1), L≤1+SL \leq 1 + \sqrt{S} with SS the sum, and E[S]≤E[S]E[\sqrt{S}] \leq \sqrt{E[S]} (the variance of S\sqrt{S} is non-negative), so E[L]≤1+n−1≤1+nE[L] \leq 1 + \sqrt{n - 1} \leq 1 + \sqrt{n}. Universality bounds only pairs of keys, and some universal families reach this order of growth; the family of Theorem 27.9 behaves on these keys almost like a random function, for which the longest chain grows like ln⁡n/ln⁡ln⁡n\ln n / \ln \ln n, about 5 here.

Exercise 27.11 ★★★

Prove that the shuffle of Listing 27.2 produces each of the n!n! orders with probability 1/n!1/n!.

Solution

Solution of Exercise 27.11.

The shuffle makes n−1n - 1 choices, the ii-th uniform among n−in - i values, independently: n(n−1)⋯2=n!n(n - 1) \cdots 2 = n! equally likely sequences. Each sequence gives one order, and each order comes from exactly one sequence: given the final order, position 00 must hold its final element, which fixes the first choice (the position where that element was); the list after the first swap is then fixed, and the same argument applies to position 11 and the rest. A bijection between n!n! equally likely sequences and the n!n! orders gives each order the probability 1/n!1/n!. For n=3n = 3, the second line of Exercise 27.2’s output shows it.

Exercise 27.12 ★★★

A skip list keeps its keys in a sorted linked list, and each key also in the lists of levels 1,2,…1, 2, \dots with probability 1/21/2 for each further level, independently. Implement search and insertion, and measure the number of nodes a search looks at for n=210,…,216n = 2^{10}, \dots, 2^{16} against 2log⁡2n2 \log_2 n.

Solution

Solution of Exercise 27.12.

    def search(self, key):
        """The largest key <= key at level 0, and the number of nodes looked at."""
        level, node, looked = len(self.head) - 1, None, 0
        while level >= 0:
            nxt = (node[level + 1] if node else self.head[level])
            while nxt is not None and nxt[0] <= key:
                node, looked = nxt, looked + 1
                nxt = node[level + 1]
            looked += 1  # the node that stopped us, or the end of the level
            level -= 1
        return node, looked
Search in a skip list, from the top level down code/bachelor-2/27-randomised-algorithms/listings/exo_skiplist.py
$ python exo_skiplist.py
      n  levels  nodes looked at (mean of 1,000 searches)  2 log2 n
   1024      11                                       20.7      20.0
   4096      11                                       21.8      24.0
  16384      15                                       28.7      28.0
  65536      21                                       35.8      32.0
Output 27.19. The cost of a search against 2log⁡2n2 \log_2 n.

The number of levels is about log⁡2n\log_2 n, since a key reaches level ℓ\ell with probability 2−ℓ2^{-\ell}. Followed backwards, a search goes up a level each time the node reached was promoted, with probability 1/21/2, and left otherwise: on average two steps per level, so about 2log⁡2n2 \log_2 n nodes, as measured. The insertion follows the same path and links the new node on each of its levels.

27.8 Problem: The weakest links of the friendship network

Problem 27.1

Weekend problem — The weakest links of the friendship network

The town records the friendships of its people in a table. The program below finds the groups, then runs Karger’s algorithm 10,000 times on the larger group, and on its core: the people left after setting aside, again and again, those with fewer than two friends left.

$ python friends_problem.py
39 people have friends, 50 friendships; two groups of 29 and 10 with no friendship between
the smaller group's friendships: 15-27 16-19 16-21 16-27 17-19 17-23 19-23 22-27 23-24 23-26 23-27
the larger group: 29 people, 39 friendships; smallest cut 1, found in 7,287 of 10,000 runs
   bound 2/(n(n-1)) = 0.0025; 7 different minimum cuts found, the most frequent:
      one side [18]: 1124 runs
      one side [18, 20]: 1056 runs
      one side [25]: 1056 runs
its core: 22 people, 32 friendships; smallest cut 2, found in 6,995 of 10,000 runs
   bound 2/(n(n-1)) = 0.0043; 15 different minimum cuts found, the most frequent:
      one side [36]: 563 runs
      one side [28, 29, 30, 32, 34, 36, 37, 38, 39]: 558 runs
      one side [7]: 518 runs
   the cut that sets apart the 9 people [28, 29, 30, 32, 34, 36, 37, 38, 39]: 558 runs
Output 27.11. The friendship network: its groups, and Karger’s algorithm on the larger group and on its core.

Part I — Contractions by hand.

  1. The table has friendships for 39 of the 120 people. What is the minimum cut of the network of these 39 people, and what does Karger’s algorithm return on it?
  2. Draw the smaller group, with its 11 friendships. Which people have a single friend?
  3. What is the minimum cut of the smaller group, and how many minimum cuts does it have?
  4. Contract, in this order, 16-19, 17-23, 19-23, 23-27, 15-27, 22-27, 23-24, 23-26. Which two vertices are left, and what cut is returned?
  5. Give an order of contractions that returns a cut of size 2 or more.
  6. On a graph with a vertex of degree 1, can Karger’s algorithm return a cut of size 1 that does not separate that vertex? Discuss.

Part II — The bound.

  1. Why does every vertex of the multigraph have degree at least cc at every stage, when cc is the size of a minimum cut?
  2. Prove that the product ∏r=3n(1−2/r)\prod_{r = 3}^{n} (1 - 2/r) equals 2/(n(n−1))2/(n(n - 1)).
  3. Compute the bound for the larger group and for its core, and compare with the lines of Output 27.11.
  4. Show that a graph on nn vertices has at most n(n−1)/2n(n - 1)/2 minimum cuts. (Each one is found with probability at least 2/(n(n−1))2/(n(n - 1)) by the same run.)
  5. Give a graph with exactly n(n−1)/2n(n - 1)/2 minimum cuts: a cycle of nn vertices.
  6. Why is the measured success on the larger group, about 73%73\%, so far above the bound?

Part III — Amplification.

  1. How many runs does Theorem 27.19 require to find a minimum cut of the core with probability at least 99%99\%?
  2. Using the measured rate of the cut that sets apart nine people, 558558 in 10,00010{,}000, how many runs give 99%99\% for that cut?
  3. The program keeps the smallest cut over the runs. Why is the answer of NN runs never larger than the answer of one run, and when is it wrong?
  4. Is the amplified algorithm Las Vegas or Monte Carlo? Can its answer be checked cheaply?
  5. Compare the cost of n2ln⁡nn^2 \ln n runs with that of computing a maximum flow from one vertex to each of the n−1n - 1 others, as in Chapter 26.
  6. Describe how stopping the contractions at about n/2n/\sqrt{2} vertices and recursing twice could reduce the number of repetitions needed (no proof).

Part IV — What the measurements say.

  1. The larger group has 7 minimum cuts. Identify them in the friendship table: they are the friendships whose removal splits the group.
  2. The seven are found about equally often, close to 7,287/77{,}287/7 runs each. What do the other 2,7132{,}713 runs return, and why is that not an error of the program?
  3. In the core, the minimum cut is 2. Which two friendships join the nine people 28,29,30,32,34,36,37,38,3928, 29, 30, 32, 34, 36, 37, 38, 39 to the others?
  4. The core has 15 minimum cuts found. How many of them separate a single person, and why do those people have exactly two friends in the core?
  5. The nine people’s cut is found in 5.6%5.6\% of the runs and the bound is 0.43%0.43\%. State the problem’s result: Karger’s bound, success at least 2/(n(n−1))2/(n(n - 1)), against the rates measured on the town’s network.
  6. If the town wanted the weakest link between two real communities rather than a person with few friends, what should it change in the question?
Solution

Solution of Problem 27.1.

1. 00: the two groups have no friendship between them. Contractions never join the groups, so every run ends with the two groups and returns the empty cut.

2. A cycle 16, 19, 23, 27; a triangle 17, 19, 23; and the people 15 and 22 (friends of 27), 21 (of 16), 24 and 26 (of 23), each with a single friend.

3. 11, and there are five minimum cuts, one for each of the five people with a single friend: their friendships are the only ones whose removal splits the group.

4. The contractions build one vertex from all but 21; the two vertices are 21 and the rest, and the cut is the friendship 16-21.

5. Contract 16-21 first, then 15-27, 22-27, 23-27, 17-23, 19-23, 23-24, 23-26: the two vertices are {16,21}\{16, 21\} and the rest, joined by 16-19 and 16-27.

6. Yes: any of the five minimum cuts may come out, and each separates a different person. The algorithm finds a minimum cut, not a particular one.

7. A vertex of the multigraph stands for a set XX of people, and its edges are the friendships between XX and the rest: a cut of the original graph, so at least cc.

8. ∏r=3nr−2r\prod_{r = 3}^{n} \frac{r - 2}{r}: the numerators are 1,…,n−21, \dots, n - 2 and the denominators 3,…,n3, \dots, n, which leaves 1⋅2(n−1)n\frac{1 \cdot 2}{(n - 1)n}.

9. 2/(29⋅28)≈0.00252/(29 \cdot 28) \approx 0.0025 and 2/(22⋅21)≈0.00432/(22 \cdot 21) \approx 0.0043, as printed; the measured rates of each single cut, about 0.100.10 and 0.040.04 to 0.0560.056, are far above.

10. The events “the run returns CC”, for different minimum cuts CC, are disjoint, and each has probability at least 2/(n(n−1))2/(n(n - 1)); their probabilities add up to at most 11.

11. In a cycle every vertex has degree 2, every cut has at least 2 edges, and any 2 of the nn edges form a cut of size 2 (the two arcs between them): (n2)=n(n−1)/2\binom{n}{2} = n(n - 1)/2 minimum cuts.

12. The bound is for one given minimum cut in the worst graph. The group has 7, each found about 10%10\% of the time; and its many people with one or two friends make most contractions harmless.

13. 22⋅212ln⁡100≈1,064\frac{22 \cdot 21}{2} \ln 100 \approx 1{,}064 runs.

14. (1−0.0558)N≤0.01(1 - 0.0558)^N \leq 0.01 for N≥ln⁡100/−ln⁡(1−0.0558)≈81N \geq \ln 100 / -\ln(1 - 0.0558) \approx 81 runs.

15. It is the smallest over the runs, so at most any single one. It is wrong when no run found a minimum cut; the answer is then a cut, but not a minimum one.

16. Monte Carlo: the running time is fixed and the answer may be too large. Checking that a cut is minimum needs a minimum-cut computation, so there is no cheap check.

17. One maximum flow by Edmonds–Karp costs O(nm2)O(n m^2) for mm edges, and n−1n - 1 of them, from a fixed vertex to each other one, find a minimum cut (the fixed vertex is on one side, some other on the other side): O(n2m2)O(n^2 m^2). The n2ln⁡nn^2 \ln n runs of almost-linear cost give O(n2mlog⁡n)O(n^2 m \log n) up to the cost of the unions, which is smaller when mm is large.

18. Most of the risk is in the last contractions, when 2/r2/r is large. Contracting to about n/2n/\sqrt{2} vertices keeps a given minimum cut with probability about 1/21/2; recursing twice on the result, independently, spends the repetitions where the risk is.

19. The seven friendships 4-9, 12-20, 18-20, 25-37, 29-31, 33-35 and 33-39; the program prints the smaller side of the three most frequent: 18 (friend of 20 only), 25, and 18 with 20.

20. Cuts of 2 or more friendships: a run fails when it contracts one of the seven friendships before the end. It still returns a cut, only not a minimum one; the minimum over several runs corrects it.

21. 1-28 and 5-37: from the larger part, 28 is a friend of 1, and 37 of 5.

22. Ten, those with exactly two friends in the core: a cut that separates one person consists of that person’s friendships, so it has size 2 exactly when the person has two.

23. The result: Karger’s bound guarantees that a given minimum cut is found with probability at least 2/(n(n−1))2/(n(n - 1)), 0.43%0.43\% for the 22 people of the core; the cut that sets apart nine people is found in 5.6%5.6\% of the runs, and a minimum cut of some kind in about 70%70\%.

24. Ask for a cut whose two sides both have at least a given number of people, or divide the size of a cut by the size of its smaller side; the single people with two friends then stop being the answer. That problem is harder, and contraction alone no longer solves it.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো