Algorithm Search⌘K

Algorithmintro

Quine-McCluskey algorithm

Also called method of prime implicants, tabulation method.

Finds all prime implicants by merging minterms that differ in one bit, level by level, then chooses a minimum cover with a prime implicant table.

Time
O(n^2 3^n + p^m poly(p, m)) worstO(n^2 2^n) best
Space
O(n 3^n) extra
Where
m = the number of on-set minterms; n = the number of variables; p = the number of prime implicants
Properties
deterministicexactofflinerecursive
Origin
Willard Van Orman Quine, Edward J. McCluskey, 1956

The Quine-McCluskey algorithm finds a minimum sum of products of a Boolean function given by its minterms and its don't-cares. It solves two-level logic minimization exactly, in two phases. Phase 1 lists all prime implicants: it merges pairs of cubes that differ in one variable, level by level, and the cubes that never merge are the primes. Phase 2 builds the prime implicant table, with one row for each minterm of the on-set and one column for each prime, and chooses a cheapest set of columns that covers every row. This is a set cover problem. Phase 1 takes time O(n23n)O(n^2 3^n) in the worst case. Phase 2 is exponential in the worst case, since the table problem is NP-hard. The method is the textbook exact algorithm and the reference that heuristics such as Espresso are tested against.

In plain words

Write each input where the function is 1, or where you do not care, as a string of bits. Look for two strings that differ in one place only, such as 1000 and 1001. Together they make the shorter rule 100-, where the dash means "either". Do this for every pair, then do it again with the new strings, and so on. A string that never joins a partner is a prime: it cannot grow any larger.

Then make a table. Each row is an input where the function must be 1, and each column is a prime. Some rows have one prime only, so you must take it. After that, take the cheapest set of the other primes that covers the rows that are left. When the choice is not forced, try the options and keep the best.

The problem

The input is nn, the on-set F⊆{0,…,2n−1}F \subseteq \{0, \ldots, 2^n - 1\} and the don't-care set DD, both as lists of minterm numbers. The output is a set CC of cubes with F⊆⋃C⊆F∪DF \subseteq \bigcup C \subseteq F \cup D of least cost (number of cubes, number of literals), compared in this order. A cube is a string over {0,1,−}\{0, 1, -\}, and the minterm numbers use x1x_1 as the high bit.

The algorithm

  1. PRIMES(n, F, D) ▷ phase 1
  2. 1level ← { the minterm cube of m : m ∈ F ∪ D }
  3. 2while level ≠ ∅ do
  4. 3next ← ∅, merged ← ∅
  5. 4for each cube c ∈ level and each position i with c[i] = 0 do
  6. 5d ← c with c[i] set to 1
  7. 6if d ∈ level then add c with c[i] set to - to next
  8. 7add c and d to merged
  9. 8add every cube of level - merged to primes
  10. 9level ← next
  11. return primes
  12. COVER(F, primes) ▷ phase 2, weight(p) = (1, literals of p)
  13. 10SOLVE(F, primes, ∅, (0, 0)); return the best set found
  14. SOLVE(left, cols, chosen, spent)
  15. repeat
  16. 11if left = ∅ then record chosen if spent < best; return
  17. 12if spent ≥ best then return
  18. 13for each row m ∈ left with exactly one prime p in cols: move p to chosen, remove its rows
  19. 14drop a column j if some other column k covers every row of j in left and weight(k) ≤ weight(j)
  20. 15drop a row m if some other row's set of primes is a subset of the set of m
  21. until L13 to L15 change nothing
  22. 16m ← the row of left with the fewest primes in cols
  23. for each prime p of row m, cheapest first do
  24. SOLVE(left minus the rows of p, cols - {p}, chosen + {p}, spent + weight(p))

Phase 1 keeps one level of cubes at a time. Level kk holds the implicants with kk dashes. Line L5 builds the partner dd of cc across position ii, and line L6 merges the two into a cube with one more dash. Because dd is made from cc by changing one bit, the two always have their dashes in the same places. A cube that merges with no partner is prime, and line L8 keeps it. A cube can be made from more than one pair, as 10-- is made from 10-0 with 10-1 and from 100- with 101-, and the set next keeps it once.

Phase 2 is a branch and bound on the prime table. Lines L13 to L15 are the classic reductions. An essential row forces its prime. A column that covers no more rows than another, at no lower weight, can go. A row that every cover of another row also covers can go. When none of them applies, what is left is the cyclic core, and line L16 branches on its hardest row. When two columns cover the same rows at the same weight, line L14 drops only one of them, the one with the larger index.

Example

Take F={4,8,10,11,12,15}F = \{4, 8, 10, 11, 12, 15\} and D={9,14}D = \{9, 14\} over x1x2x3x4x_1 x_2 x_3 x_4.

Phase 1, level by level:

level cubes merges primes kept by L8
0 0100, 1000, 1001, 1010, 1100, 1011, 1110, 1111 10 pairs, for example 0100 + 1100 = -100 none
1 -100, 1-00, 10-0, 100-, 1-10, 10-1, 101-, 11-0, 1-11, 111- 1--0, 1-1- and 10--, each from two pairs -100
2 1--0, 1-1-, 10-- none 1--0, 1-1-, 10--

So the primes are -100, 1--0, 1-1- and 10--. The prime table has the rows of FF only, not of DD:

prime 4 8 10 11 12 15
-100 x x
1--0 x x x
1-1- x x x
10-- x x x

Phase 2:

step line action left
1 L13 row 4 has only -100, and row 15 has only 1-1-: take both {8}
2 L14 1--0 and 10-- both cover row 8 with weight (1, 2): drop 10-- {8}
3 L13 row 8 now has only 1--0: take it ∅
4 L11 record the cover with cost (3, 7)

The result is x2xˉ3xˉ4+x1xˉ4+x1x3x_2 \bar{x}_3 \bar{x}_4 + x_1 \bar{x}_4 + x_1 x_3. The cover with 10-- in place of 1--0 has the same cost. No branch was needed, because the table had no cyclic core.

Correctness

Phase 1 is correct by induction on the level: level kk is exactly the set of implicants with kk dashes. A cube with k+1k + 1 dashes lies in F∪DF \cup D exactly when its two halves across any one dash do, and lines L4 to L6 build it from those halves. A cube is not prime exactly when one of its literals can be removed, that is, when it is one half of an implicant at the next level, which is the test of lines L6 and L7. So the cubes kept by line L8 are all the primes, and only them.

Phase 2 is correct because each reduction keeps the optimum of the current subproblem: a row with one prime must use it, a dominated column can be swapped for its dominator in any solution at no extra cost, and a dominated row is covered whenever the smaller row is. The branch of line L16 tries every prime of a row that some prime must cover, and the bound of line L12 cuts only branches that cannot beat the best cover found. By Quine's theorem every minimum cover is made of primes, so the best prime cover is a minimum cover. The full proof gives the details.

Proof: Quine-McCluskey lists all primes and returns a minimum coverfull

We write A=F∪DA = F \cup D, and for a cube cc we write dash(c)\mathrm{dash}(c) for the number of its dashes. An implicant is a cube c⊆Ac \subseteq A. For a cube cc and a position ii with c[i]=−c[i] = -, the two halves of cc at ii are cc with c[i]c[i] set to 0 and cc with c[i]c[i] set to 1. Their union is cc.

Lemma 1 (levels). At the start of round kk of the loop of line L2 (rounds count from 0), the set level is exactly Lk={c:c⊆A, dash(c)=k}L_k = \{c : c \subseteq A,\ \mathrm{dash}(c) = k\}.

Proof. By induction on kk. For k=0k = 0, line L1 sets level to the minterms of AA, which are the implicants with no dash. Assume the claim for kk. Line L6 adds a cube ee to next only when its two halves at some position ii are both in level, so both are implicants by the hypothesis, and ee, their union, is an implicant with k+1k + 1 dashes. Conversely, let ee be an implicant with k+1k + 1 dashes, and let ii be any dash of ee. Its two halves cc (with 0 at ii) and dd (with 1 at ii) are subcubes of ee, so they are implicants with kk dashes, and they are in level. Line L4 reaches cc and ii, line L5 builds exactly dd, and line L6 adds ee. So next =Lk+1= L_{k+1} after the round, and line L9 makes it the new level. □\square

Lemma 2 (primes). In round kk, a cube c∈Lkc \in L_k is put in merged by line L7 exactly when cc is not prime.

Proof. By the literal form of primality (see the prime implicant page), an implicant cc is not prime exactly when, for some literal position ii of cc, the cube ee equal to cc with c[i]c[i] set to −- is an implicant. Such an ee has k+1k + 1 dashes, and cc is one of its halves at ii. The other half c′c' is a subcube of ee, so it is in LkL_k. If c[i]=0c[i] = 0, then line L4 reaches cc and ii, line L5 builds c′c', and line L7 marks cc. If c[i]=1c[i] = 1, then line L4 reaches c′c' and ii, line L5 builds cc, and line L7 marks cc as the cube dd. Conversely, line L7 marks a cube only when it is a half of a cube that line L6 adds, and that cube is an implicant by Lemma 1, so the marked cube is not prime. □\square

Theorem 1. PRIMES returns every prime implicant of ff once, and nothing else.

Proof. Every implicant cc is in exactly one level, Ldash(c)L_{\mathrm{dash}(c)}, by Lemma 1. Line L8 adds cc in that round exactly when cc is not in merged, that is, by Lemma 2, when cc is prime. A level LkL_k with k>nk > n is empty, so the loop of line L2 stops after at most n+1n + 1 rounds. □\square

For phase 2, let PP be the list of primes and w(p)=(1,∣p∣)w(p) = (1, |p|), where ∣p∣|p| is the number of literals. Weights add coordinatewise and compare lexicographically. For a set left⊆F\mathrm{left} \subseteq F and a set cols⊆P\mathrm{cols} \subseteq P, let OPT(left,cols)\mathrm{OPT}(\mathrm{left}, \mathrm{cols}) be the least weight of a set S⊆colsS \subseteq \mathrm{cols} whose union contains left\mathrm{left}, or ∞\infty if there is none.

Lemma 3 (reductions). Each change that lines L13, L14 and L15 make to (left, cols, chosen, spent) keeps the value spent+OPT(left,cols)\mathrm{spent} + \mathrm{OPT}(\mathrm{left}, \mathrm{cols}).

Proof. Line L13: let row mm have the single prime pp in cols. Every feasible SS for (left, cols) holds pp, since nothing else covers mm. So OPT(left,cols)=w(p)+OPT(left∖p,cols∖{p})\mathrm{OPT}(\mathrm{left}, \mathrm{cols}) = w(p) + \mathrm{OPT}(\mathrm{left} \setminus p, \mathrm{cols} \setminus \{p\}), and moving pp to chosen adds w(p)w(p) to spent. When several rows force primes at once, apply this to each forced prime in turn.

Line L14: let j≠kj \ne k be in cols, with j∩left⊆kj \cap \mathrm{left} \subseteq k and w(k)≤w(j)w(k) \le w(j). Take an optimal SS for (left, cols). If j∈Sj \in S, then S′=(S∖{j})∪{k}S' = (S \setminus \{j\}) \cup \{k\} still covers left and has weight at most w(S)w(S), because weights are nonnegative. So some optimal set avoids jj, and dropping jj keeps OPT. Line L14 drops one column per pass and then recomputes, so the dominating column kk is in cols when jj is dropped. Two equal columns cannot both go in one pass.

Line L15: let m≠m2m \ne m_2 be rows of left with rows(m2)⊆rows(m)\mathrm{rows}(m_2) \subseteq \mathrm{rows}(m), where rows(x)\mathrm{rows}(x) is the set of primes of cols that contain xx. Every set that covers m2m_2 holds a prime of rows(m2)\mathrm{rows}(m_2), which also covers mm. So the feasible sets for left and for left∖{m}\mathrm{left} \setminus \{m\} are the same, and OPT does not change. Again one row goes per pass, so two equal rows cannot both go. □\square

Lemma 4 (search). A call SOLVE(left, cols, chosen, spent) records, among other sets, a set of weight spent+OPT(left,cols)\mathrm{spent} + \mathrm{OPT}(\mathrm{left}, \mathrm{cols}) unless the best recorded weight is already at most that value. Every recorded set covers FF when the root call starts with left=F\mathrm{left} = F.

Proof. By induction on ∣cols∣|\mathrm{cols}|. By Lemma 3, the reductions keep spent+OPT\mathrm{spent} + \mathrm{OPT}. Each pass that changes something removes a row or a column, so the repeat loop stops. If some row has no prime in cols, OPT is ∞\infty and the return loses nothing. If left is empty, OPT is (0,0)(0, 0) and line L11 records chosen when it is better. If spent is at least the best weight, line L12 returns, and the claim holds since OPT≥(0,0)\mathrm{OPT} \ge (0, 0). Otherwise let mm be the row of line L16. Every feasible set for (left, cols) holds some prime pp of row mm, so OPT(left,cols)=min⁡p(w(p)+OPT(left∖p,cols∖{p}))\mathrm{OPT}(\mathrm{left}, \mathrm{cols}) = \min_p \big(w(p) + \mathrm{OPT}(\mathrm{left} \setminus p, \mathrm{cols} \setminus \{p\})\big), and the loop calls SOLVE on each term, with one column fewer. The claim follows from the induction hypothesis. A set is recorded only at line L11, when left is empty, and the rows removed on the way were covered by chosen primes or were dominated rows, which a chosen prime of the dominating row covers. □\square

Theorem 2. COVER returns a set of primes of least weight whose union contains FF, and it is a minimum cover of ff.

Proof. The set of all primes covers FF, since each minterm of FF is an implicant and lies in some prime. It has at most ∣P∣|P| cubes, so the initial bound (∣P∣+1,0)(|P| + 1, 0) is larger than its weight, and Lemma 4 applied to the root call shows that the returned set has weight OPT(F,P)\mathrm{OPT}(F, P). Each prime lies in AA, so the union of the returned set lies between FF and AA, and it is a cover. By Quine's theorem (see the prime implicant page), every minimum cover for this cost consists of primes, so no cover has a smaller weight. ■\blacksquare

Termination. Phase 1 stops after at most n+1n + 1 rounds. In phase 2 each recursive call has one column fewer, so the depth is at most ∣P∣|P|, and each repeat loop stops as shown in Lemma 4.

Complexity

Phase 1. Level kk holds at most (nk)2n−k\binom{n}{k} 2^{n-k} cubes, the number of cubes with kk dashes, and the sum over kk is 3n3^n. Each cube is handled once at its level. Line L4 tries at most nn positions, and lines L5 and L6 build a string and look it up in a hash set in O(n)O(n) time. So phase 1 takes O(n23n)O(n^2 3^n) time and O(n3n)O(n 3^n) space in the worst case, on the word RAM with hashing in expected O(n)O(n) time per string. In terms of the truth table size N=2nN = 2^n, this is O(Nlog⁡23log⁡2N)O(N^{\log_2 3} \log^2 N), and log⁡23≈1.585\log_2 3 \approx 1.585. When no two minterms of F∪DF \cup D merge, only level 0 is built, which takes O(n22n)O(n^2 2^n) time.

Phase 2. Each pass of lines L11 to L15 takes time polynomial in pp and mm, and each pass removes a row or a column, so a node of the search tree costs poly(p,m)\mathrm{poly}(p, m). Each branch adds one prime and covers at least one more row, so the tree has depth at most mm and at most pp children per node, and at most pmp^m leaves. This bound is exponential. No polynomial bound is expected, because the table problem is set cover, which is NP-hard, and the number of primes pp can be of order 3n/n3^n / n by the result of Chandra and Markowsky.

Properties

  • Exact. The output is a minimum cover for the cost (number of cubes, number of literals).
  • Deterministic. The order of the primes and the tie rules of lines L14 and L16 fix the output.
  • Lists all primes. Phase 1 builds every implicant of F∪DF \cup D on the way, which is the main cost for functions with many don't-cares.
  • Needs minterms. The input is a list of minterms, so the method needs time at least proportional to ∣F∪D∣|F \cup D|, which can be 2n2^n even when the function has a short SOP.

Variants and improvements

  • McCluskey's grouping. Sort the cubes of a level by their number of ones. Two cubes can merge only if their counts differ by one, so only neighbor groups are compared. This is the form of the 1956 paper and of most textbooks. A hash set, as in line L6, does the same job.
  • The consensus method. Quine (1955) builds the primes from any SOP of ff, not from the minterms: add the consensus of two cubes and remove cubes that other cubes contain, until nothing changes.
  • Recursive prime generation. Split ff by the Shannon expansion and build the primes of ff from the primes of its two cofactors. This avoids the minterm list.
  • Implicit methods. Coudert and Madre store the set of primes and the table as BDDs or ZDDs, and so handle functions with far more primes than one can list. Coudert (1994) surveys them.
  • Other table solvers. Petrick's method lists every irredundant cover of the table. A pseudo-Boolean or integer program solves it with one 0-1 variable per prime. Greedy set cover gives a cover within a factor 1+ln⁡m1 + \ln m of the fewest cubes, with no search.
  • Multiple outputs. Give each cube a tag with the set of outputs whose on-set or don't-care set holds it. Two cubes merge when they differ in one bit, and the tag of the result is the intersection of the tags.

When to use it

Use Quine-McCluskey when the function has few variables, up to about 10 to 15 with a moderate number of primes, and you need a proved minimum, or a reference to test a heuristic against. For larger functions, the number of primes and the cyclic core grow too fast. Then use Espresso, which does not list the primes and gives a prime and irredundant cover, or an exact implicit method. For hand work on four variables, a Karnaugh map shows the same primes as rectangles.

Pitfalls

  • Merging cubes with different dashes. The cubes 1-0 and 10- differ in one bit if one ignores the dashes, but they do not merge: their union is not a cube. Line L5 avoids this, because it builds the partner from cc itself.
  • Keeping only the last level. Primes come from every level. A version that returns only the cubes of the last level, in place of line L8, misses -100 in the example.
  • Don't-cares in the wrong phase. Line L1 must use F∪DF \cup D, or the primes are too small. The table of line L13 must use FF only, or the cover pays to cover points that need no cover.
  • Stopping after the essential primes. After line L13, a greedy choice of the rest is not exact. The cyclic function ∑m(1,2,3,4,5,6)\sum m(1, 2, 3, 4, 5, 6) has no essential prime at all.
  • Dropping both of two equal columns. If line L14 drops each column that another one dominates, two equal columns drop each other and a row can lose all its primes. Drop one at a time, with a tie rule.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

quine_mccluskey.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quine-mccluskey/. The authors are listed in prov/N0CYS5.jsonl.

"""The Quine-McCluskey method for two-level minimization.

A cube over n variables is a string of length n over '0', '1' and '-'.
Position i is the variable x_{i+1}; '1' is the literal x, '0' is the
literal x', and '-' means that the variable is free. A minterm is an
integer m in [0, 2^n); its bit for x_1 is the most significant bit.
"""

from typing import Iterable

Cube = str


def minterm_cube(n: int, m: int) -> Cube:
    """The cube of one minterm."""
    return format(m, "b").zfill(n) if n else ""


def cube_minterms(c: Cube) -> list[int]:
    """All minterms of a cube, in increasing order."""
    out = [0]
    for ch in c:
        if ch == "0":
            out = [2 * m for m in out]
        elif ch == "1":
            out = [2 * m + 1 for m in out]
        else:
            out = [2 * m + b for m in out for b in (0, 1)]
    return sorted(out)


def literals(c: Cube) -> int:
    return sum(ch != "-" for ch in c)


def cost(cover: Iterable[Cube]) -> tuple[int, int]:
    """The cost of a cover: the number of cubes, then the number of literals."""
    cubes = list(cover)
    return len(cubes), sum(literals(c) for c in cubes)


def prime_implicants(n: int, on: Iterable[int], dc: Iterable[int] = ()) -> list[Cube]:
    """Phase 1: all prime implicants of the function with on-set on and don't-care set dc."""
    level = {minterm_cube(n, m) for m in set(on) | set(dc)}  # @line L1
    primes: list[Cube] = []
    while level:  # @line L2
        nxt: set[Cube] = set()  # @line L3
        merged: set[Cube] = set()
        for c in level:  # @line L4
            for i, ch in enumerate(c):
                if ch == "0":
                    d = c[:i] + "1" + c[i + 1:]  # @line L5
                    if d in level:
                        nxt.add(c[:i] + "-" + c[i + 1:])  # @line L6
                        merged.add(c)  # @line L7
                        merged.add(d)
        primes.extend(sorted(level - merged))  # @line L8
        level = nxt  # @line L9
    return primes


def minimum_cover(on: Iterable[int], primes: list[Cube]) -> list[Cube]:
    """Phase 2: a cheapest set of primes that covers every on-set minterm.

    It takes the essential primes, removes dominated rows and columns,
    and branches on the cyclic core. The result is exact for the cost
    (number of cubes, number of literals).
    """
    covers = [set(cube_minterms(p)) for p in primes]
    weight = [(1, literals(p)) for p in primes]
    todo = frozenset(on)
    best: list[list[int] | None] = [None]
    best_cost = [(len(primes) + 1, 0)]

    def add(a: tuple[int, int], b: tuple[int, int]) -> tuple[int, int]:
        return a[0] + b[0], a[1] + b[1]

    def solve(left: frozenset[int], cols: set[int], chosen: list[int], spent: tuple[int, int]) -> None:
        cols = set(cols)
        chosen = list(chosen)
        while True:
            if not left:  # @line L11
                if spent < best_cost[0]:
                    best_cost[0], best[0] = spent, chosen
                return
            if spent >= best_cost[0]:  # @line L12: bound
                return
            rows = {m: {j for j in cols if m in covers[j]} for m in left}
            if any(not r for r in rows.values()):
                return
            ess = {next(iter(r)) for r in rows.values() if len(r) == 1}  # @line L13
            if ess:
                for j in sorted(ess):
                    chosen.append(j)
                    spent = add(spent, weight[j])
                    cols.discard(j)
                left = frozenset(m for m in left if not any(m in covers[j] for j in ess))
                continue
            # @line L14: column dominance (a prime that covers no more and costs no less)
            dropped = False
            for j in sorted(cols):
                cj = covers[j] & left
                for k in sorted(cols):
                    if k != j and cj <= covers[k] and weight[k] <= weight[j] and (cj != covers[k] & left or weight[k] < weight[j] or k < j):
                        cols.discard(j)
                        dropped = True
                        break
                if dropped:
                    break
            if dropped:
                continue
            # @line L15: row dominance (a row whose primes include all primes of another row)
            for m in sorted(left):
                if any(m2 != m and rows[m2] <= rows[m] for m2 in left):
                    left = left - {m}
                    dropped = True
                    break
            if dropped:
                continue
            break
        m = min(left, key=lambda x: (len(rows[x]), x))  # @line L16: branch
        for j in sorted(rows[m], key=lambda j: (weight[j], j)):
            solve(left - covers[j], cols - {j}, chosen + [j], add(spent, weight[j]))

    solve(todo, set(range(len(primes))), [], (0, 0))  # @line L10
    assert best[0] is not None
    return sorted(primes[j] for j in best[0])


def quine_mccluskey(n: int, on: Iterable[int], dc: Iterable[int] = ()) -> list[Cube]:
    """A minimum sum of products of the function, as a list of cubes."""
    on = set(on)
    primes = prime_implicants(n, on, dc)
    return minimum_cover(on, primes)
test_quine_mccluskey.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quine-mccluskey/. The authors are listed in prov/N0CYS5.jsonl.

import itertools
import random

from quine_mccluskey import cost, cube_minterms, minimum_cover, prime_implicants, quine_mccluskey


def all_cubes(n: int) -> list[str]:
    return ["".join(t) for t in itertools.product("01-", repeat=n)]


def mask(c: str) -> int:
    out = 0
    for m in cube_minterms(c):
        out |= 1 << m
    return out


def brute_primes(n: int, on: set[int], dc: set[int]) -> list[str]:
    """Every cube inside on | dc that no larger such cube contains."""
    allowed = sum(1 << m for m in on | dc)
    imps = [c for c in all_cubes(n) if mask(c) & ~allowed == 0 and mask(c)]
    out = []
    for c in imps:
        bigger = (c[:i] + "-" + c[i + 1:] for i in range(n) if c[i] != "-")
        if not any(mask(d) & ~allowed == 0 for d in bigger):
            out.append(c)
    return sorted(out)


def brute_min_cost(n: int, on: set[int], dc: set[int]) -> tuple[int, int]:
    """The least (cubes, literals) over all sets of implicants that cover the on-set."""
    if not on:
        return (0, 0)
    allowed = sum(1 << m for m in on | dc)
    target = sum(1 << m for m in on)
    imps = [c for c in all_cubes(n) if mask(c) and mask(c) & ~allowed == 0]
    masks = [mask(c) for c in imps]
    lits = [sum(ch != "-" for ch in c) for c in imps]
    for k in range(1, len(imps) + 1):
        best = None
        for combo in itertools.combinations(range(len(imps)), k):
            got = 0
            for j in combo:
                got |= masks[j]
            if got & target == target:
                s = sum(lits[j] for j in combo)
                if best is None or s < best:
                    best = s
        if best is not None:
            return (k, best)
    raise AssertionError("no cover")


def is_cover(n: int, cover: list[str], on: set[int], dc: set[int]) -> bool:
    got: set[int] = set()
    for c in cover:
        got |= set(cube_minterms(c))
    return on <= got <= on | dc


def test_textbook_example() -> None:
    # f = sum of m(4, 8, 10, 11, 12, 15) + d(9, 14)
    on, dc = {4, 8, 10, 11, 12, 15}, {9, 14}
    assert sorted(prime_implicants(4, on, dc)) == sorted(["-100", "10--", "1--0", "1-1-"])
    cover = quine_mccluskey(4, on, dc)
    # Two covers tie at 3 cubes and 7 literals.
    assert cover in (["-100", "10--", "1-1-"], ["-100", "1--0", "1-1-"])
    assert cost(cover) == (3, 7)


def test_cyclic_core() -> None:
    # Every minterm is in two primes and no prime is essential.
    on = {0, 1, 2, 5, 6, 7}
    assert sorted(prime_implicants(3, on)) == sorted(["-01", "0-0", "00-", "1-1", "11-", "-10"])
    cover = quine_mccluskey(3, on)
    assert cost(cover) == (3, 6)
    assert is_cover(3, cover, on, set())


def test_edges() -> None:
    assert quine_mccluskey(3, set()) == []
    assert quine_mccluskey(3, set(range(8))) == ["---"]
    assert quine_mccluskey(2, {0}, {1, 2, 3}) == ["--"]
    assert quine_mccluskey(0, {0}) == [""]
    # Parity needs every minterm as its own cube.
    odd = {m for m in range(16) if bin(m).count("1") % 2}
    assert cost(quine_mccluskey(4, odd)) == (8, 32)


def test_primes_against_brute_force() -> None:
    rng = random.Random(7)
    for n in range(1, 5):
        for _ in range(60):
            on = {m for m in range(2 ** n) if rng.random() < 0.4}
            dc = {m for m in range(2 ** n) if m not in on and rng.random() < 0.2}
            assert sorted(prime_implicants(n, on, dc)) == brute_primes(n, on, dc)


def test_all_three_variable_functions() -> None:
    for bits in range(2 ** 8):
        on = {m for m in range(8) if bits >> m & 1}
        cover = quine_mccluskey(3, on)
        assert is_cover(3, cover, on, set())
        assert cost(cover) == brute_min_cost(3, on, set())


def test_random_with_dont_cares() -> None:
    rng = random.Random(11)
    for n, trials in ((3, 200), (4, 80)):
        for _ in range(trials):
            on = {m for m in range(2 ** n) if rng.random() < 0.35}
            dc = {m for m in range(2 ** n) if m not in on and rng.random() < 0.25}
            cover = quine_mccluskey(n, on, dc)
            assert is_cover(n, cover, on, dc)
            assert set(cover) <= set(prime_implicants(n, on, dc))
            assert cost(cover) == brute_min_cost(n, on, dc)


def test_minimum_cover_given_primes() -> None:
    on = {0, 1, 2, 5, 6, 7}
    primes = prime_implicants(3, on)
    cover = minimum_cover(on, primes)
    assert len(cover) == 3 and is_cover(3, cover, on, set())

History

Quine (1952) asked for the shortest normal formula of a truth function and showed that it is a sum of prime implicants. In 1955 he gave the consensus method for finding them. McCluskey (1956) gave the tabular method that merges minterms grouped by their number of ones, and the prime implicant table for the choice of primes. The same year, Petrick gave an algebraic method for solving the table. The method was the standard way to minimize switching circuits on early computers, and it is still the exact method in textbooks.

References

  1. W. V. Quine, The problem of simplifying truth functions, American Mathematical Monthly 59(8), 521 to 531, 1952, prime implicants and the theorem that a shortest normal formula is a sum of prime implicants
  2. W. V. Quine, A way to simplify truth functions, American Mathematical Monthly 62(9), 627 to 631, 1955, the consensus method for listing the prime implicants
  3. E. J. McCluskey, Minimization of Boolean functions, Bell System Technical Journal 35(6), 1417 to 1444, 1956, the tabular method for the prime implicants, grouped by the number of ones, and the prime implicant table
  4. Gary D. Hachtel and Fabio Somenzi, Logic Synthesis and Verification Algorithms, Kluwer, 1996, Chapter 4, Synthesis of Two-Level Circuits (Quine's theorem, the Quine-McCluskey procedure and the covering table)
  5. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 7, Two-Level Combinational Logic Optimization (exact minimization, the covering matrix and its reductions)
  6. Olivier Coudert, Two-level logic minimization, an overview, Integration, the VLSI Journal 17(2), 97 to 140, 1994, the cyclic core and the reductions of the covering matrix by essentiality and dominance

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example