---
title: "Boolean Algebra and Combinational Circuits"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 27
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 27 — Boolean Algebra and Combinational Circuits

The adder inside a processor adds two 64-bit numbers in a fraction of a nanosecond. It is built from gates, each of which knows only one or two bits and computes a function as simple as “both” or “either”. This chapter is about how such gates are combined: how any function of bits can be written with them, how to write it with few, why one kind of gate is enough, and how the arrangement of the gates, not their number, decides the speed of an adder. The circuits are built and run in a small simulator, in which a circuit is what it is in the hardware: a [directed acyclic graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-dag) of gates.

**You already know.**

Gates and the half adder were built in the first book; the second built an adder and a [multiplexer](#def-b1-combinational-circuits-mux). Formulas, their truth tables and the normal forms DNF and CNF are in [Definition 10.7](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-normal-forms); DAGs and their longest paths in Chapters [24](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#ch-b1-graph-traversals) and [25](https://one-course.com/books/computer-science/3/en/chapter/25-shortest-paths#ch-b1-shortest-paths).

## 27.1 Boolean functions and canonical forms

**Definition 27.1 (Boolean function).**

A *Boolean function* of $n$ variables is a function $f\colon \{0, 1\}^n \to \{0, 1\}$. It is given by its truth table, $2^n$ rows; so there are $2^{2^n}$ Boolean functions of $n$ variables.

We write $x'$ for the negation of $x$, $xy$ for the conjunction and $x + y$ for the disjunction. These operations obey the laws of *Boolean algebra*: commutativity and associativity of $+$ and of the product; each distributes over the other, $x(y + z) = xy + xz$ and $x + yz = (x + y)(x + z)$; $x + 0 = x$, $x \cdot 1 = x$, $x + x'
= 1$, $x x' = 0$; and De Morgan’s laws $(x + y)' = x' y'$, $(xy)' = x' + y'$. Each is checked on the four (or eight) rows of a truth table. Boole set them out in 1854 as laws of thought; in 1938 Shannon showed that they describe circuits of relays.

![George Boole, whose book of 1854 set out these laws as the laws of thought. Portrait by an unknown artist, public domain.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-combinational-circuits/img-46fb80d69d1b.jpg)

*George Boole, whose book of 1854 set out these laws as the laws of thought. Portrait by an unknown artist, public domain.*

**Definition 27.2 (Minterm, maxterm, canonical forms).**

A *minterm* of $n$ variables is a product in which every variable appears once, plain or negated: it is 1 on exactly one row. A *maxterm* is a sum in which every variable appears once: it is 0 on exactly one row. The *canonical sum of products* of $f$ is the sum of the minterms of the rows where $f$ is 1; its *canonical product of sums* is the product of the maxterms of the rows where $f$ is 0.

Both equal $f$: the sum is 1 exactly on the rows of its [minterms](#def-b1-combinational-circuits-canonical), and the product 0 exactly on the rows of its [maxterms](#def-b1-combinational-circuits-canonical). They are the DNF and CNF of [Chapter 10](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#ch-b1-propositional-logic) read off a truth table, and they prove that negation, conjunction and disjunction can express every [Boolean function](#def-b1-combinational-circuits-boolean-function).

```python
def sum_of_products(f, names):
    terms = []
    for row in product((0, 1), repeat=len(names)):
        if f(*row):  # a minterm: true on this row only
            terms.append("".join(literal(n, v, 1) for n, v in zip(names, row)))
    return " + ".join(terms)


def product_of_sums(f, names):
    factors = []
    for row in product((0, 1), repeat=len(names)):
        if not f(*row):  # a maxterm: false on this row only
            literals = [literal(n, v, 0) for n, v in zip(names, row)]
            factors.append("(" + " + ".join(literals) + ")")
    return "".join(factors)
```

***Listing 27.1.** The canonical forms from the truth table code/bachelor-1/27-combinational-circuits/listings/canonical.py*

```
$ python canonical.py
a b c | maj
0 0 0 | 0
0 0 1 | 0
0 1 0 | 0
0 1 1 | 1
1 0 0 | 0
1 0 1 | 1
1 1 0 | 1
1 1 1 | 1
sum of products: a'bc + ab'c + abc' + abc
product of sums: (a + b + c)(a + b + c')(a + b' + c)(a' + b + c)
functions of n variables: [4, 16, 256, 65536, 4294967296]
```

***Output 27.1.** The majority of three bits, its two canonical forms, and the number of functions of 1 to 5 variables.*

**Definition 27.3 (Combinational circuit).**

A *combinational circuit* is a [directed acyclic graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-dag) whose sources are the inputs, whose other [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) are logic gates, each fed by the [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) it has [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) from, and some of whose [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) are marked as outputs. Its outputs depend only on its current inputs.

The simulator stores the gates in the order they were added; a gate may only use wires that exist already, so that order is topological, and evaluation is one pass, as for the DAG paths of [Chapter 25](https://one-course.com/books/computer-science/3/en/chapter/25-shortest-paths#ch-b1-shortest-paths).

```python
    def gate(self, op, *ins):
        """Add a gate whose inputs are existing wires; return its output wire."""
        known = set(self.inputs) | {w for w, _, _ in self.gates}
        assert all(i in known for i in ins), "a gate may only use existing wires"
        wire = f"w{len(self.gates)}"
        self.gates.append((wire, op, ins))
        return wire

    def evaluate(self, values):
        """values: input wire -> 0 or 1. Returns the value of every output."""
        v = dict(values)
        for wire, op, ins in self.gates:  # every input is computed before
            v[wire] = OPS[op]([v[i] for i in ins])
        return {name: v[w] for name, w in self.outputs.items()}

    def delay(self):
        """The longest path from an input to an output, counted in gates."""
        depth = {i: 0 for i in self.inputs}
        for wire, _, ins in self.gates:
            depth[wire] = 1 + max((depth[i] for i in ins), default=0)
        return max(depth[w] for w in self.outputs.values())
```

***Listing 27.2.** The simulator: adding a gate, evaluating, and the delay code/bachelor-1/27-combinational-circuits/listings/circuit.py*

## 27.2 Simplification

The majority function needs four products of three literals in its canonical form, but $ab + ac + bc$ will do. Algebra finds it: $abc$ can be repeated, $a'bc + abc = bc$, and so on. A picture finds it faster.

**Definition 27.4 (Karnaugh map).**

A *Karnaugh map* of a function of four variables is its truth table arranged as a $4 \times 4$ grid, rows labelled by $ab$ and columns by $cd$ in the order $00, 01, 11, 10$, so that two neighbouring cells, the first and last of a row or column included, differ in exactly one variable.

Two neighbouring 1 cells merge into a product without the variable in which they differ; four cells in a $2 \times 2$ square or a row of four lose two variables; eight cells lose three. Groups must be rectangles of $1$, $2$, $4$ or $8$ cells, possibly wrapping around the edges.

**Definition 27.5 (Implicant, prime implicant, essential prime implicant, don’t-care).**

An *implicant* of $f$ is a product of literals that is 1 only where $f$ is 1. It is *prime* if removing any literal makes it cover a 0 of $f$, and *essential* if it is the only prime implicant covering some 1 of $f$. A *don’t-care condition* is a row whose output does not matter, because it never occurs; it may be covered or not, as suits the simplification.

A minimal sum of products is made of [prime implicants](#def-b1-combinational-circuits-implicant) (a [non-prime](#def-b1-combinational-circuits-implicant) one can lose a literal) and contains every [essential](#def-b1-combinational-circuits-implicant) one. The program finds the [prime implicants](#def-b1-combinational-circuits-implicant) by merging terms that differ in one variable, round after round, the method of Quine and McCluskey; with four variables, a [Karnaugh map](#def-b1-combinational-circuits-karnaugh) shows the same groups at a glance.

```python
def merge(s, t):
    """Two terms such as '0-11' and '1-11' that differ in one position give '--11'."""
    diff = [i for i in range(len(s)) if s[i] != t[i]]
    if len(diff) == 1 and "-" not in (s[diff[0]], t[diff[0]]):
        return s[:diff[0]] + "-" + s[diff[0] + 1:]
    return None


def prime_implicants(ones, dont_care=(), n=4):
    terms = {format(m, f"0{n}b") for m in set(ones) | set(dont_care)}
    primes = set()
    while terms:
        merged, used = set(), set()
        for s in terms:
            for t in terms:
                m = merge(s, t)
                if m:
                    merged.add(m)
                    used |= {s, t}
        primes |= terms - used  # a term that merges with nothing is prime
        terms = merged
    return sorted(primes)
```

***Listing 27.3.** [Prime implicants](#def-b1-combinational-circuits-implicant) by repeated merging; `-` marks a variable that has gone code/bachelor-1/27-combinational-circuits/listings/karnaugh.py*

```
$ python karnaugh.py
ab\cd 00  01  11  10
  00   1   1   .   1
  01   .   1   1   1
  11   .   .   .   1
  10   1   1   .   1
prime implicants: cd', b'd', b'c', a'c'd, a'bd, a'bc
essential: cd', b'c'
```

***Output 27.2.** The map of a function of four variables, its six [prime implicants](#def-b1-combinational-circuits-implicant) and the two [essential](#def-b1-combinational-circuits-implicant) ones.*

![The map of covered by three prime implicants: f = cd' + b'c' + a'bd. The two essential ones leave the cells 5 and 7 bare; a'bd covers both, where a'c'd or a'bc would cover only one.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-combinational-circuits/fig-bccd70641c09.svg)

*The map of [Output 27.2](#out-b1-combinational-circuits-qm) covered by three [prime implicants](#def-b1-combinational-circuits-implicant): $f = cd' +
b'c' + a'bd$. The two [essential](#def-b1-combinational-circuits-implicant) ones leave the cells 5 and 7 bare; $a'bd$ covers both, where $a'c'd$ or $a'bc$ would cover only one.*

A seven-segment display shows a digit with seven lit bars, named $a$ to $g$. Its [decoder](#def-b1-combinational-circuits-mux) takes the digit in four bits; the codes 10 to 15 never occur, and the don’t-cares let the groups grow.

```
$ python seven_segment.py
a = c + b'd' + bd + a           correct on 0-9: True
b = c'd' + cd + b'              correct on 0-9: True
c = d + c' + b                  correct on 0-9: True
d = cd' + b'd' + b'c + bc'd + a correct on 0-9: True
e = cd' + b'd'                  correct on 0-9: True
f = c'd' + bd' + bc' + a        correct on 0-9: True
g = b'c + bc' + a + cd'         correct on 0-9: True
42 literals in all, against 196 in the canonical sums
```

***Output 27.3.** The seven segments, each simplified with the codes 10 to 15 as don’t-cares, and checked on the ten digits. The variables are $abcd$, $a$ the high bit.*

## 27.3 NAND alone is enough

**Definition 27.6 (Functionally complete set).**

A set of Boolean operations is *functionally complete* if every [Boolean function](#def-b1-combinational-circuits-boolean-function) of any number of variables can be computed by a circuit of gates from the set.

The canonical forms show that $\{\text{NOT}, \text{AND}, \text{OR}\}$ is complete; by De Morgan, so are $\{\text{NOT},
\text{AND}\}$ and $\{\text{NOT}, \text{OR}\}$.

**Proposition 27.7 (NAND is complete).**

$\{\text{NAND}\}$ is [functionally complete](#def-b1-combinational-circuits-complete).

**Proof.** $x' = \text{NAND}(x, x)$ and $xy = \text{NAND}(x, y)'$, so NOT and AND are expressed with NAND, and $\{\text{NOT},
\text{AND}\}$ is complete. ∎

```python
def nand_not(c, x):
    return c.gate("NAND", x, x)


def nand_and(c, x, y):
    return nand_not(c, c.gate("NAND", x, y))


def nand_or(c, x, y):
    return c.gate("NAND", nand_not(c, x), nand_not(c, y))  # De Morgan


def nand_xor(c, x, y):
    n = c.gate("NAND", x, y)
    return c.gate("NAND", c.gate("NAND", x, n), c.gate("NAND", y, n))
```

***Listing 27.4.** NOT, AND, OR and XOR from NAND gates code/bachelor-1/27-combinational-circuits/listings/nand_only.py*

```
$ python nand_only.py
NOT: NAND gates 1, delay 1, correct: True
AND: NAND gates 2, delay 2, correct: True
OR : NAND gates 3, delay 2, correct: True
XOR: NAND gates 4, delay 3, correct: True
```

***Output 27.4.** Each construction checked on its four inputs.*

![NOT, AND and OR from NAND gates, as in : one, two and three gates.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-combinational-circuits/fig-b8e1e1abbb7c.svg)

*NOT, AND and OR from NAND gates, as in [Listing 27.4](#lst-b1-combinational-circuits-nand): one, two and three gates.*

Not every set is complete. A function is *monotone* if raising an input from 0 to 1 never lowers the output; AND and OR are monotone, and so is any circuit of AND and OR gates, by induction along the DAG. NOT is not monotone, so $\{\text{AND}, \text{OR}\}$ is not complete ([Exercise 27.10](#exo-b1-combinational-circuits-10)). Sheffer showed in 1913 that one operation, the “stroke” now called NAND, suffices for all of Boolean algebra. In hardware a NAND gate is the cheapest: a few transistors used as switches, the physics of which belongs to the physics books.

**History — Gates on a chip.**

In the 1960s, gates stopped being wired one by one from separate parts and began to be made together on one chip of silicon, an integrated circuit. In 1966 Texas Instruments announced its 7400 series of such chips in cheap plastic packages. The 7400 itself holds four independent two-input NAND gates in a package of 14 pins: three for each gate, and two for the power supply. Circuits like those of this chapter were then built by wiring such chips together on a board.

![A 7400 chip in its plastic package with two rows of seven pins. Inside are the four NAND gates; the notch marks the end where pin 1 is. Photograph: Mister rf, CC BY-SA 4.0.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-combinational-circuits/img-4fe8d791176f.jpg)

*A 7400 chip in its plastic package with two rows of seven pins. Inside are the four NAND gates; the notch marks the end where pin 1 is. Photograph: Mister rf, CC BY-SA 4.0.*

## 27.4 Arithmetic and routing

**Definition 27.8 (Full adder, ripple-carry adder).**

A *full adder* adds three bits $a$, $b$ and a carry in $c$: its sum is $a \oplus b \oplus c$ and its carry out is $ab + c(a \oplus b)$, where $\oplus$ is XOR. A *ripple-carry adder* of $n$ bits chains $n$ full adders, the carry out of each feeding the carry in of the next.

Subtraction comes free: in two’s complement, $a - b = a + b' + 1$, where $b'$ inverts every bit; XOR gates with a control bit invert $b$ on demand, and the same bit is the first carry in.

The carry is the trouble: bit $i$ cannot finish before bit $i - 1$, and the last carry waits for the whole chain. The way out is to compute every carry directly from the inputs. Write $g_i = a_i b_i$ (bit $i$ *generates* a carry) and $p_i = a_i \oplus b_i$ (it *propagates* the carry it receives). Then $c_{i+1} = g_i + p_i c_i$, and unrolling,

$$
c_{i+1} = g_i + p_i g_{i-1} + p_i p_{i-1} g_{i-2} + \dots + p_i p_{i-1} \cdots p_0 c_0.
$$

**Definition 27.9 (Generate and propagate, carry-lookahead adder).**

The signals $g_i$ and $p_i$ are the *generate and propagate signals*. A *carry-lookahead adder* computes the carries of a block of bits by the unrolled formula, with one level of AND gates and one OR gate per carry.

```python
def lookahead_block(c, a, b, cin):
    """Four bits: c_{i+1} = g_i + p_i g_{i-1} + ... + p_i ... p_0 c_0, two levels."""
    g = [c.gate("AND", x, y) for x, y in zip(a, b)]
    p = [c.gate("XOR", x, y) for x, y in zip(a, b)]
    carries = [cin]
    for i in range(4):
        terms = [g[i]]
        for j in range(i - 1, -2, -1):  # g_j (or c_0) carried through p_{j+1} ... p_i
            src = g[j] if j >= 0 else cin
            terms.append(c.gate("AND", src, *p[j + 1:i + 1]))
        carries.append(c.gate("OR", *terms))
    sums = [c.gate("XOR", p[i], carries[i]) for i in range(4)]
    return sums, carries[4]
```

***Listing 27.5.** A 4-bit lookahead block code/bachelor-1/27-combinational-circuits/listings/adders.py*

![Left, a 4-bit ripple-carry adder: each full adder waits for the carry of the one before. Right, a lookahead block: generate and propagate in one gate delay, all four carries in two more, the sums in one more.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-combinational-circuits/fig-319d81abf1f1.svg)

*Left, a 4-bit [ripple-carry adder](#def-b1-combinational-circuits-adder): each [full adder](#def-b1-combinational-circuits-adder) waits for the carry of the one before. Right, a lookahead block: generate and propagate in one gate delay, all four carries in two more, the sums in one more.*

**Definition 27.10 (Multiplexer, decoder).**

A $2^k$-to-1 *multiplexer* has $2^k$ data inputs and $k$ select inputs, and outputs the data input whose number the select inputs spell. A $k$-to-$2^k$ *decoder* has $k$ inputs and $2^k$ outputs, of which exactly the one numbered by the inputs is 1.

A 2-to-1 [multiplexer](#def-b1-combinational-circuits-mux) is $s' x_0 + s x_1$; a [decoder](#def-b1-combinational-circuits-mux) is one AND gate per [minterm](#def-b1-combinational-circuits-canonical). [Multiplexers](#def-b1-combinational-circuits-mux) *route* information: they choose which result goes on.

**Definition 27.11 (Arithmetic and logic unit).**

An *arithmetic and logic unit* (ALU) computes, from two operands and an operation code, one of several results, chosen by [multiplexers](#def-b1-combinational-circuits-mux), and *flags* that describe it: $Z$ (zero), $N$ (negative, the top bit), $C$ (carry out) and $V$ (overflow in two’s complement).

```python
def alu():
    c = Circuit(*[f"a{i}" for i in range(4)], *[f"b{i}" for i in range(4)],
                "op1", "op0")
    sub = c.gate("AND", "op1", "op0")
    carry, result = sub, []  # a - b = a + (not b) + 1
    for i in range(4):
        b = c.gate("XOR", f"b{i}", sub)
        s, carry = full_adder(c, f"a{i}", b, carry)
        both, either = c.gate("AND", f"a{i}", f"b{i}"), c.gate("OR", f"a{i}", f"b{i}")
        logic = mux(c, "op0", both, either)
        result.append(mux(c, "op1", logic, s))
        if i == 3:
            same_signs = c.gate("NOT", c.gate("XOR", "a3", b))
            overflow = c.gate("AND", "op1", same_signs, c.gate("XOR", s, "a3"))
    for i, r in enumerate(result):
        c.outputs[f"r{i}"] = r
    c.outputs |= {"Z": c.gate("NOR", *result), "N": result[3],
                  "C": c.gate("AND", "op1", carry), "V": overflow}
    return c
```

***Listing 27.6.** A 4-bit ALU: AND, OR, addition and subtraction code/bachelor-1/27-combinational-circuits/listings/alu.py*

```
$ python alu.py
71 gates, delay 13; all 1024 cases correct: True
ADD  2  3 ->  5 = 0101  Z=0 N=0 C=0 V=0
ADD  7  1 ->  8 = 1000  Z=0 N=1 C=0 V=1
ADD  9  9 ->  2 = 0010  Z=0 N=0 C=1 V=1
SUB  5  7 -> 14 = 1110  Z=0 N=1 C=0 V=0
SUB  6  6 ->  0 = 0000  Z=1 N=0 C=1 V=0
AND 12 10 ->  8 = 1000  Z=0 N=1 C=0 V=0
OR  12 10 -> 14 = 1110  Z=0 N=1 C=0 V=0
```

***Output 27.5.** Checked against integer arithmetic on all 1024 cases; $7 + 1$ overflows in signed 4-bit arithmetic, and $9 + 9$ carries out.*

Overflow happens when the two operands of the addition have the same sign and the result the other one; the circuit tests exactly that, on the top bits.

## 27.5 Propagation delay

**Definition 27.12 (Propagation delay, longest delay path).**

Each gate takes a small time, its *propagation delay*, to update its output. The delay of a circuit is the largest total delay along a path from an input to an output, a *longest delay path*. With every gate counted as one delay, as in the simulator, it is the longest path of the DAG, counted in gates.

```
$ python adders.py
4 bits, ripple-carry:  20 gates, delay  9, all 512 sums correct: True
4 bits, lookahead   :  26 gates, delay  4, all 512 sums correct: True
8 bits, ripple-carry:  40 gates, delay 17, all 131072 sums correct: True
8 bits, lookahead   :  52 gates, delay  6, all 131072 sums correct: True
16 bits: delay  33 rippling, 10 with lookahead blocks
32 bits: delay  65 rippling, 18 with lookahead blocks
64 bits: delay 129 rippling, 34 with lookahead blocks
```

***Output 27.6.** Sizes and delays of the two adders, both checked on every input for 4 and 8 bits.*

The [ripple-carry adder](#def-b1-combinational-circuits-adder) has delay $2n + 1$ ([Exercise 27.11](#exo-b1-combinational-circuits-11)): linear in the number of bits. A lookahead block has delay 4 whatever the carry in, at the price of more gates, and of gates with many inputs, which real hardware limits. Rippling between blocks of four still costs two delays per block. Lookahead applied again to the blocks, in a tree of lookahead units, brings the delay to $O(\log n)$; processors add 64 bits that way, within a clock cycle.

## 27.6 Exercises

**Exercise 27.1 ★.**

Give the truth table of the circuit $f = \text{OR}(\text{AND}(a, \text{NOT}(b)), \text{AND}(b, c))$, and its delay.

**Solution of Exercise 27.1.**

$f = ab' + bc$ is 1 on the rows $abc = 011, 100, 101, 111$ and 0 on the others. The longest path is NOT, AND, OR: delay 3.

**Exercise 27.2 ★.**

The function $f(a, b, c)$ is 1 exactly when an odd number of its inputs are 1. Write its [canonical sum of products](#def-b1-combinational-circuits-canonical), and explain why no Karnaugh grouping shortens it.

**Solution of Exercise 27.2.**

$f = a'b'c + a'bc' + ab'c' + abc$. Two neighbouring cells of a [Karnaugh map](#def-b1-combinational-circuits-karnaugh) differ in one variable, so their numbers of 1 inputs differ by one and their values of $f$ differ: no two 1 cells are neighbours, and no group is larger than one cell.

**Exercise 27.3 ★.**

Using the map of [Output 27.2](#out-b1-combinational-circuits-qm), find another minimal sum of products, if there is one, and say why every minimal sum has at least three products.

**Solution of Exercise 27.3.**

The [essential](#def-b1-combinational-circuits-implicant) $cd'$ and $b'c'$ cover every 1 but the cells 5 and 7. Only $a'bd$ among the [prime implicants](#def-b1-combinational-circuits-implicant) covers both; $a'c'd$ covers 5 and $a'bc$ covers 7, which needs two products. So $f = cd' + b'c' + a'bd$ is the only minimal sum; it needs three products, since the two [essential](#def-b1-combinational-circuits-implicant) ones must be there and do not cover everything.

**Exercise 27.4 ★.**

What does the ALU of [Listing 27.6](#lst-b1-combinational-circuits-alu) output for the operation code 11 with $a = 3$ and $b = 9$? Give the four flags, and interpret them as unsigned and as signed numbers.

**Solution of Exercise 27.4.**

The code 11 is subtraction: $3 - 9 + 16 = 10 = 1010$, with $Z = 0$, $N = 1$, $C = 0$, $V = 1$. Unsigned, $C = 0$ means a borrow: $3 < 9$ and the result has wrapped round. Signed, $9$ is $-7$ and $3 - (-7) = 10$ does not fit in 4 bits: $V =
1$, and the result read as $-6$ is wrong.

**Exercise 27.5 ★★.**

A student labels the columns of a [Karnaugh map](#def-b1-combinational-circuits-karnaugh) $00, 01, 10, 11$ and the rows likewise, then groups the two middle 1s of the row $ab = 00$ of a function that is 1 on the [minterms](#def-b1-combinational-circuits-canonical) 1 and 2 only, writing $a'b'$ times “whatever $cd$ is”. What went wrong, and what is the correct sum?

**Solution of Exercise 27.5.**

In the order $00, 01, 10, 11$, the middle columns $01$ and $10$ sit side by side but differ in two variables, $c$ and $d$: they are not neighbours, and the two cells do not form a product. The [minterms](#def-b1-combinational-circuits-canonical) 1 and 2 stay apart: $f = a'b'c'd +
a'b'cd'$. The Gray order $00, 01, 11, 10$ makes the drawing tell the truth.

**Exercise 27.6 ★★.**

This [full adder](#def-b1-combinational-circuits-adder) assembles its carry differently. On which row is it wrong, and why on that row only?

```python
c = Circuit("a", "b", "cin")
c.outputs["s"] = c.gate("XOR", c.gate("XOR", "a", "b"), "cin")
c.outputs["cout"] = c.gate("XOR", c.gate("AND", "a", "b"),
                           c.gate("AND", "cin", c.gate("OR", "a", "b")))
```

***Listing 27.7.** Another carry code/bachelor-1/27-combinational-circuits/listings/exo_carry_xor.py*

```
wrong on a=1 b=1 cin=1: carry 0
```

***Output 27.7.** Every row checked. Some lines are left out.*

**Solution of Exercise 27.6.**

It computes $ab \oplus c(a + b)$. The two products are both 1 only when $a = b = 1$ and $c = 1$, and then XOR gives 0 where the carry is 1. On every other row at most one of them is 1, and XOR agrees with OR. The textbook carry $ab + c(a
\oplus b)$ has the same property, so there either gate works; with $a + b$ inside, only OR does.

**Exercise 27.7 ★★.**

Build a 2-to-1 and a 4-to-1 [multiplexer](#def-b1-combinational-circuits-mux) in the simulator, and test them on every input.

**Solution of Exercise 27.7.**

```python
def mux2(c, s, x0, x1):
    return c.gate("OR", c.gate("AND", c.gate("NOT", s), x0), c.gate("AND", s, x1))


def mux4():
    """Output x[2 s1 + s0]: two levels of 2-to-1 multiplexers."""
    c = Circuit("s1", "s0", "x0", "x1", "x2", "x3")
    low, high = mux2(c, "s0", "x0", "x1"), mux2(c, "s0", "x2", "x3")
    c.outputs["out"] = mux2(c, "s1", low, high)
    return c
```

*[Multiplexers](#def-b1-combinational-circuits-mux) code/bachelor-1/27-combinational-circuits/exercises/mux.py*

The 4-to-1 [multiplexer](#def-b1-combinational-circuits-mux) is two 2-to-1 [multiplexers](#def-b1-combinational-circuits-mux) on $s_0$ followed by one on $s_1$: 12 gates, delay 5. The test tries the 64 inputs.

**Exercise 27.8 ★★.**

Build a circuit that outputs $a < b$ for two 4-bit unsigned numbers, test it on every input, and give its delay.

**Solution of Exercise 27.8.**

```python
def less_than():
    c = Circuit(*[f"a{i}" for i in range(4)], *[f"b{i}" for i in range(4)])
    eq = [c.gate("NOT", c.gate("XOR", f"a{i}", f"b{i}")) for i in range(4)]
    lt = [c.gate("AND", c.gate("NOT", f"a{i}"), f"b{i}") for i in range(4)]
    terms = [c.gate("AND", lt[i], *eq[i + 1:]) if i < 3 else lt[3] for i in range(4)]
    c.outputs["lt"] = c.gate("OR", *terms)
    return c
```

*$a < b$ on four bits code/bachelor-1/27-combinational-circuits/exercises/compare.py*

$a < b$ when, at some bit $i$, $a_i = 0$ and $b_i = 1$ while all higher bits are equal. One OR of four products: 20 gates, delay 4 (XOR, NOT, AND, OR). The test tries the 256 pairs.

**Exercise 27.9 ★★.**

Count the monotone [Boolean functions](#def-b1-combinational-circuits-boolean-function) of $n$ variables for $n \leq 3$, by program and by argument for $n \leq 2$.

**Solution of Exercise 27.9.**

```python
def monotone_count(n):
    rows = list(product((0, 1), repeat=n))
    count = 0
    for table in product((0, 1), repeat=len(rows)):
        f = dict(zip(rows, table))
        if all(f[x] <= f[y] for x in rows for y in rows
               if all(a <= b for a, b in zip(x, y))):
            count += 1
    return count
```

*Monotone functions, by [brute force](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#def-b1-backtracking-exhaustive) code/bachelor-1/27-combinational-circuits/exercises/monotone.py*

The program finds 2, 3, 6 and 20 for $n = 0, 1, 2, 3$, against $2, 4, 16, 256$ functions in all. For $n = 1$: the constants and $x$ ($x'$ is not monotone). For $n = 2$: the constants, $x$, $y$, $xy$ and $x + y$; any other function is 1 on some row and 0 on a row above it.

**Exercise 27.10 ★★★.**

Prove that $\{\text{NOR}\}$ is [functionally complete](#def-b1-combinational-circuits-complete), and that $\{\text{AND}, \text{OR}\}$ is not.

**Solution of Exercise 27.10.**

$x' = \text{NOR}(x, x)$ and $x + y = \text{NOR}(x, y)'$: NOR expresses NOT and OR, a complete set by De Morgan. For the second part, every circuit of AND and OR gates computes a monotone function, by induction along a [topological order](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-topo): the inputs are monotone, and AND and OR of monotone functions are monotone, since they are monotone in each argument. NOT is not monotone, so no such circuit computes it.

**Exercise 27.11 ★★★.**

Prove that in the simulator’s model the $n$-bit [ripple-carry adder](#def-b1-combinational-circuits-adder) has delay $2n + 1$ for $n \geq 1$, and the lookahead block delay 4.

**Solution of Exercise 27.11.**

In stage $i$, $p_i = a_i \oplus b_i$ and $a_i b_i$ have depth 1. Let $d_i$ be the depth of the carry $c_i$: $d_0 = 0$, and $c_1 = a_0 b_0 + p_0 c_0$ has depth 3. For $i \geq 1$, $p_i c_i$ has depth $d_i + 1 \geq 4$ and the OR $d_i + 2$, so $d_i =
2i + 1$ for $i \geq 1$. The sums $s_i = p_i \oplus c_i$ have depth at most $d_i + 1 \leq 2n$, so the carry out, of depth $2n + 1$, is the longest. In a lookahead block, $g_i$ and $p_i$ have depth 1, every AND of them (and of $c_0$) depth 2, every carry, an OR, depth 3, and every sum depth 4.

**Exercise 27.12 ★★★.**

Build a 4-bit [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) multiplier from AND gates and [full adders](#def-b1-combinational-circuits-adder), test it on all 256 inputs, and give its size and delay.

**Solution of Exercise 27.12.**

```python
def multiplier(n=4):
    c = Circuit(*[f"a{i}" for i in range(n)], *[f"b{i}" for i in range(n)])
    zero = c.gate("AND", "a0", c.gate("NOT", "a0"))
    acc = [c.gate("AND", f"a{i}", "b0") for i in range(n)] + [zero] * n
    for j in range(1, n):  # add (a AND b_j) shifted j places
        row = [c.gate("AND", f"a{i}", f"b{j}") for i in range(n)]
        carry = zero
        for i in range(n):
            acc[i + j], carry = full_adder(c, acc[i + j], row[i], carry)
        acc[n + j] = carry
    for k, w in enumerate(acc):
        c.outputs[f"p{k}"] = w
    return c
```

*An [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) multiplier code/bachelor-1/27-combinational-circuits/exercises/multiplier.py*

The 16 partial products $a_i b_j$ cost 16 AND gates; three rows of four [full adders](#def-b1-combinational-circuits-adder) add them, row $j$ shifted $j$ places. The circuit has 78 gates, including two that make a constant 0, and delay 18; the test compares it with $x \times y$ on the 256 pairs.

## 27.7 Problem: An arithmetic unit from one kind of gate

**Problem 27.1.**

Weekend problem — An arithmetic unit from one kind of gate

A factory makes only NAND gates. How many does a half adder need? The program tries every circuit of $k$ two-input NAND gates, for $k = 1, 2, \dots$; each signal is kept as its truth table on the four rows, a number of four bits.

```python
def search(k):
    """(number of circuits tried, first circuit found or None). A circuit is a list of
    gates, each a pair of earlier signals; a signal is a 4-bit truth table."""
    tried, found = 0, None

    def extend(signals, gates):
        nonlocal tried, found
        if len(gates) == k:
            tried += 1
            if found is None and set(TARGETS.values()) <= set(signals[2:]):
                found = list(gates)
            return
        for i, j in combinations_with_replacement(range(len(signals)), 2):
            out = ~(signals[i] & signals[j]) & 0b1111  # NAND on all four rows at once
            extend(signals + [out], gates + [(i, j)])

    extend([A, B], [])
    return tried, found
```

***Listing 27.8.** Every NAND circuit of $k$ gates code/bachelor-1/27-combinational-circuits/listings/min_nand.py*

```
$ python min_nand.py
gates 1:      3 circuits, half adder: none
gates 2:     18 circuits, half adder: none
gates 3:    180 circuits, half adder: none
gates 4:   2700 circuits, half adder: none
gates 5:  56700 circuits, half adder: [(0, 1), (0, 2), (1, 2), (2, 2), (3, 4)]
```

***Output 27.8.** The number of circuits tried, and the first half adder found; signals 0 and 1 are $a$ and $b$, signal $i + 2$ the output of gate $i$.*

**Part I — Functions and forms.**

1. Give the truth tables of the sum and the carry of a half adder.
2. Write their canonical sums of products.
3. Why are `0b0011` and `0b0101` the truth tables of $a$ and $b$ ?
4. How does `\textasciitilde(x & y) & 0b1111` compute a NAND on the four rows at once?
5. How many [Boolean functions](#def-b1-combinational-circuits-boolean-function) of two variables are there? How many can a single NAND gate of $a$ and $b$ compute?
6. Why is a circuit of gates with no loop a [combinational circuit](#def-b1-combinational-circuits-combinational) ?

**Part II — Translations into NAND.**

7. Translate the carry $ab$ into NAND gates, and count them.
8. Translate the sum $a \oplus b$ with four NAND gates, and check it on the four rows.
9. Read the circuit found for $k = 5$ and explain each gate.
10. Why may the two outputs share a gate?
11. Translate a [full adder](#def-b1-combinational-circuits-adder) into NAND gates by the same method, and count them.
12. What happens to the delay when each gate is replaced by its NAND translation?

**Part III — Adders and delays.**

13. Read the sizes and delays of [Output 27.6](#out-b1-combinational-circuits-adders) .
14. Why is the delay of the [ripple-carry adder](#def-b1-combinational-circuits-adder) linear and that of a lookahead block constant?
15. Why do 8-bit lookahead adders have delay 6, and 64-bit ones 34?
16. How many inputs does the largest AND gate of a lookahead block have? What does that cost in hardware?
17. How many cases does the exhaustive check of the 8-bit adders try, and why is that a proof for 8 bits?
18. Why can the 64-bit adders not be checked the same way?

**Part IV — The smallest half adder.**

19. Show that the number of circuits of $k$ gates is $\prod_{i=0}^{k-1} \binom{i + 3}{2}$ , and check it against the output.
20. Why may a gate take the same signal twice?
21. Why do circuits with unused gates not spoil the search?
22. Why does the search for $k = 4$ prove that four gates are not enough?
23. Could a gate with three inputs, or a circuit with loops, do better? Does the search say?
24. State the named result, *the half adder needs exactly five NAND gates* .

**Solution of Problem 27.1.**

**1.** On the rows $ab = 00, 01, 10, 11$: the sum is $0, 1, 1, 0$ and the carry $0, 0, 0, 1$.

**2.** Sum $a'b + ab'$, carry $ab$.

**3.** Read from left to right, the digits of `0b0011` are the values of $a$ on the rows $00, 01, 10, 11$, and those of `0b0101` the values of $b$.

**4.** `&` works on the four rows in parallel, `\textasciitilde` inverts every bit (of an integer with infinitely many leading bits, in Python), and `& 0b1111` keeps the four rows.

**5.** $2^{2^2} = 16$. One gate computes $\text{NAND}(a, a) = a'$, $\text{NAND}(b, b) = b'$ or $\text{NAND}(a, b)$: three functions, the three circuits of one gate.

**6.** Each gate uses earlier signals only, so the circuit is a DAG, and its outputs are functions of its inputs.

**7.** $ab = \text{NAND}(n, n)$ with $n = \text{NAND}(a, b)$: two gates.

**8.** With $n = \text{NAND}(a, b)$: $\text{NAND}(\text{NAND}(a, n), \text{NAND}(b, n))$. On $00$: $n = 1$, both inner gates give 1, the result 0; on $01$ and $10$: $n = 1$ and one inner gate gives 0, the result 1; on $11$: $n = 0$, both inner gates give 1, the result 0.

**9.** Gate 0 is $n = \text{NAND}(a, b)$; gates 1 and 2 are $\text{NAND}(a, n)$ and $\text{NAND}(b, n)$; gate 3 is $\text{NAND}(n, n) = ab$, the carry; gate 4 combines gates 1 and 2 into $a \oplus b$, the sum.

**10.** Both need $\text{NAND}(a, b)$: computing it once saves a gate, $2 + 4 - 1 = 5$.

**11.** Gate by gate: two XORs (4 each), two ANDs (2 each) and an OR (3), 15 NAND gates. Sharing, as in question 10, brings a [full adder](#def-b1-combinational-circuits-adder) down to 9.

**12.** It grows: an AND becomes two levels, an OR two, an XOR three. NAND circuits are usually designed directly in two levels: a sum of products is a NAND of NANDs, by De Morgan.

**13.** 4 bits: 20 gates and delay 9 rippling, 26 gates and delay 4 with lookahead; 8 bits: 40 and 17 against 52 and 6.

**14.** Rippling, each carry waits for the one before: two gates per bit. Lookahead computes each carry of a block from the inputs by two levels of gates, whatever the block’s position.

**15.** Between blocks the carries still ripple: the carry out of block $k$ is ready two delays after its carry in. With $n / 4$ blocks the last sums come at $2(n / 4) + 2$: 6 for 8 bits, 34 for 64.

**16.** Five: the term $p_3 p_2 p_1 p_0 c_0$ of $c_4$. Gates with many inputs need more transistors in series and are slower, so real designs limit them to about four inputs and use more levels.

**17.** $2^8 \times 2^8 \times 2 = 131\,072$: every possible input, so the check covers all behaviours of this circuit.

**18.** $2^{129}$ inputs, beyond any computer: correctness for large $n$ needs a proof, by induction on the stages, as in [Exercise 27.11](#exo-b1-combinational-circuits-11).

**19.** Gate $i$ may use any unordered pair, repetitions allowed, of the $i + 2$ signals before it: $\binom{i + 3}{2}$ choices. The products $3$, $3 \times 6$, $\times 10$, $\times 15$, $\times 21$ are 3, 18, 180, 2700 and 56 700, as printed.

**20.** $\text{NAND}(x, x) = x'$: without it, NOT would need a constant input.

**21.** A circuit of $j < k$ useful gates, padded with $k - j$ more, is among the circuits of $k$ gates; extra gates do not change the signals already there.

**22.** Every circuit of at most four NAND gates appears among the 2700 tried (question 21), and none has both the sum and the carry among its signals.

**23.** The search says nothing about them: it covers loop-free circuits of two-input NAND gates, which is the claim.

**24.** *The half adder needs exactly five NAND gates*: a circuit of five computes it (question 9), and the [exhaustive search](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#def-b1-backtracking-exhaustive) over all 2901 circuits of one to four two-input NAND gates finds none.
