โ† Math|78 of 100
Discrete Mathematics

Boolean Algebra

Master Boolean operations, laws, simplification, Karnaugh maps, and circuit design.

๐Ÿ“‚ Boolean๐Ÿ“– Lesson 78 of 100๐ŸŽ“ Free Course

Advertisement

Boolean Algebra

โ„น๏ธ Why It Matters

Boolean algebra is the mathematics of logic and digital circuits. Every computer is built from logic gates implementing Boolean operations. Search engines use Boolean queries (AND, OR, NOT), databases use Boolean conditions in WHERE clauses, and machine learning decision trees make Boolean splits. Understanding Boolean algebra is essential for digital design, circuit optimization, search technology, and logical reasoning in AI.


Definitions

DfBoolean Algebra

Boolean algebra is an algebraic structure (B,+,โ‹…,โ‹…ห‰,0,1)(B, +, \cdot, \bar{\cdot}, 0, 1) where B={0,1}B = \{0, 1\}, ++ is OR, โ‹…\cdot is AND, โ‹…ห‰\bar{\cdot} is NOT, and 00 and 11 are identity elements.

DfBoolean Expression

A Boolean expression combines variables, constants 0 and 1, and operations AND (โ‹…\cdot), OR (++), NOT (โ‹…ห‰\bar{\cdot}) according to algebraic rules.

DfSum-of-Products (SOP)

A Boolean expression written as a sum (OR) of product (AND) terms: F=AB+AC+BCF = AB + AC + BC. Each product term is a minterm.

DfProduct-of-Sums (POS)

A Boolean expression written as a product (AND) of sum (OR) terms: F=(A+B)(A+C)(B+C)F = (A + B)(A + C)(B + C). Each sum term is a maxterm.

DfDuality

The dual of a Boolean expression is obtained by swapping AND with OR, and 0 with 1, while keeping variables unchanged. The dual of a true identity is also true.

DfMinterm

A minterm is a product term containing every variable exactly once, either in true or complemented form. For nn variables, there are 2n2^n minterms.

DfMaxterm

A maxterm is a sum term containing every variable exactly once. For nn variables, there are 2n2^n maxterms.


Laws of Boolean Algebra

LawAND (โ‹…\cdot)OR (++)
Identityaโ‹…1=aa \cdot 1 = aa+0=aa + 0 = a
Null (Annihilator)aโ‹…0=0a \cdot 0 = 0a+1=1a + 1 = 1
Idempotentaโ‹…a=aa \cdot a = aa+a=aa + a = a
Complementaโ‹…aห‰=0a \cdot \bar{a} = 0a+aห‰=1a + \bar{a} = 1
Commutativeaโ‹…b=bโ‹…aa \cdot b = b \cdot aa+b=b+aa + b = b + a
Associativea(bc)=(ab)ca(bc) = (ab)ca+(b+c)=(a+b)+ca + (b + c) = (a + b) + c
Distributivea(b+c)=ab+aca(b + c) = ab + aca+(bc)=(a+b)(a+c)a + (bc) = (a + b)(a + c)
Absorptiona(a+b)=aa(a + b) = aa+ab=aa + ab = a
De Morgan'sabโ€พ=aห‰+bห‰\overline{ab} = \bar{a} + \bar{b}a+bโ€พ=aห‰โ‹…bห‰\overline{a + b} = \bar{a} \cdot \bar{b}
Double Complementaห‰โ€พ=a\overline{\bar{a}} = aaห‰โ€พ=a\overline{\bar{a}} = a

Python Implementations

Truth Table Generator

from itertools import product

def truth_table(expression_func, variables):
    n = len(variables)
    header = variables + ["Result"]
    print(" | ".join(f"{v:>6}" for v in header))
    print("-" * (8 * len(header)))
    for values in product([0, 1], repeat=n):
        env = dict(zip(variables, values))
        result = expression_func(**env)
        row = [str(v) for v in values] + [str(int(result))]
        print(" | ".join(f"{v:>6}" for v in row))

# Example: F = A AND (B OR NOT C)
truth_table(
    lambda A, B, C: A & (B | (not C)),
    ['A', 'B', 'C']
)

Boolean Simplification

def boolean_simplify_sop(minterms, variables):
    """Convert minterms to SOP expression."""
    terms = []
    for m in minterms:
        term = []
        for i, v in enumerate(variables):
            if m & (1 << (len(variables) - 1 - i)):
                term.append(v)
            else:
                term.append(f"{v}'")
        terms.append("".join(term))
    return " + ".join(terms)

def boolean_simplify_pos(maxterms, variables):
    """Convert maxterms to POS expression."""
    terms = []
    for m in maxterms:
        term = []
        for i, v in enumerate(variables):
            if m & (1 << (len(variables) - 1 - i)):
                term.append(f"{v}'")
            else:
                term.append(v)
        terms.append("(" + " + ".join(term) + ")")
    return " * ".join(terms)

# SOP for F(A,B,C) = sum of minterms 1, 3, 5, 7
print(boolean_simplify_sop([1, 3, 5, 7], ['A', 'B', 'C']))
# Output: A'B'C + A'BC + AB'C + ABC

Karnaugh Map

def karnaugh_map_4var(minterms):
    """Print K-map for 4-variable function."""
    # K-map ordering: 00, 01, 11, 10
    order = [0, 1, 3, 2]
    map = [[0] * 4 for _ in range(4)]

    for m in minterms:
        row = (m >> 2) & 3
        col = m & 3
        ri = order.index(row)
        ci = order.index(col)
        map[ri][ci] = 1

    print("    AB\\CD  00   01   11   10")
    labels = ['00', '01', '11', '10']
    for i, label in enumerate(labels):
        row_str = " ".join(f"  {map[i][j]} " for j in range(4))
        print(f"     {label}  {row_str}")

    return map

# Example: F(A,B,C,D) = sum of minterms 0,1,2,5,6,7,8,9,10,14
karnaugh_map_4var([0, 1, 2, 5, 6, 7, 8, 9, 10, 14])

Logic Gate Simulation

def AND(a, b):
    return a & b

def OR(a, b):
    return a | b

def NOT(a):
    return 1 - a

def NAND(a, b):
    return NOT(AND(a, b))

def NOR(a, b):
    return NOT(OR(a, b))

def XOR(a, b):
    return AND(OR(a, b), NAND(a, b))

def XNOR(a, b):
    return NOT(XOR(a, b))

# Half adder
def half_adder(a, b):
    s = XOR(a, b)
    c = AND(a, b)
    return s, c

# Full adder
def full_adder(a, b, cin):
    s1, c1 = half_adder(a, b)
    s, c2 = half_adder(s1, cin)
    cout = OR(c1, c2)
    return s, cout

# Test
for a in range(2):
    for b in range(2):
        s, c = half_adder(a, b)
        print(f"{a} + {b} = {c}{s}")

Karnaugh Maps

โ„น๏ธ Karnaugh Map Method

Karnaugh maps provide a visual method for simplifying Boolean expressions:

  1. Draw a grid with 2n/22^{n/2} rows and 2n/22^{n/2} columns for nn variables
  2. Label rows and columns using Gray code order (adjacent cells differ by 1 bit)
  3. Place 1s in cells corresponding to minterms where F=1F = 1
  4. Group adjacent 1s in rectangles of size 2k2^k (powers of 2)
  5. Each group gives one product term: variables that don't change within the group are kept
  6. The minimal SOP is the OR of all group terms

Grouping rules:

  • Groups must be rectangular with 2k2^k cells
  • Groups may wrap around edges
  • Groups may overlap
  • Use the fewest groups possible (each group as large as possible)

Applications in AI/ML

โ„น๏ธ Applications in AI and Machine Learning

  • Decision Trees: Each internal node tests a Boolean condition; splits are Boolean expressions
  • Search Engines: Boolean queries combine terms with AND, OR, NOT for document retrieval
  • Database Queries: WHERE clauses use Boolean predicates for filtering
  • Circuit Design: Digital circuits implement Boolean functions with logic gates
  • Logic Programming: Prolog and Datalog use Boolean logic for rule evaluation
  • Formal Verification: Model checking verifies Boolean properties of hardware/software
  • Constraint Satisfaction: Boolean satisfiability (SAT) is NP-complete but has efficient solvers for many practical instances
  • Neural Networks: Threshold logic units implement Boolean functions

Common Mistakes

MistakeCorrection
Confusing AND and OR distributive lawsa+(bc)=(a+b)(a+c)a + (bc) = (a+b)(a+c), NOT a+bc=ab+aca + bc = ab + ac
Forgetting De Morgan's lawsabโ€พ=aห‰+bห‰\overline{ab} = \bar{a} + \bar{b} and a+bโ€พ=aห‰bห‰\overline{a+b} = \bar{a}\bar{b}
Ignoring self-dualitySwap AND/OR and 0/1 to get the dual; both are valid
Treating Boolean like regular algebraa+a=aa + a = a (not 2a2a); aโ‹…a=aa \cdot a = a (not a2a^2)
Confusing SOP and POSSOP = sum of products (OR of ANDs); POS = product of sums (AND of ORs)
Not using Gray code for K-mapsAdjacent cells in K-maps must differ by exactly one bit
Assuming more terms = simplerFewer terms with fewer literals = simpler expression
Forgetting XOR is not a basic Boolean opXOR can be expressed as abห‰+aห‰ba\bar{b} + \bar{a}b

Interview Questions

  1. What are the three basic Boolean operations? AND (โ‹…\cdot), OR (++), and NOT (โ‹…ห‰\bar{\cdot}). All Boolean functions can be expressed using these three.

  2. State De Morgan's laws. abโ€พ=aห‰+bห‰\overline{ab} = \bar{a} + \bar{b} and a+bโ€พ=aห‰bห‰\overline{a+b} = \bar{a}\bar{b}. These convert between AND/OR through complementation.

  3. What is the dual of a Boolean expression? Swap AND with OR and 0 with 1. The dual of a true identity is also true (Principle of Duality).

  4. How do you simplify a Boolean expression? Use algebraic laws (absorption, distribution, De Morgan's) or Karnaugh maps for visual minimization.

  5. What is a minterm and maxterm? A minterm is a product of all variables (each true or complemented); a maxterm is a sum. There are 2n2^n of each for nn variables.

  6. What is the consensus theorem? ab+aห‰c+bc=ab+aห‰cab + \bar{a}c + bc = ab + \bar{a}c. The term bcbc is redundant (consensus of abab and aห‰c\bar{a}c).

  7. How do Karnaugh maps work? Group adjacent 1s in powers of 2 on a Gray-coded grid. Each group becomes one product term. Larger groups = simpler expression.

  8. What is functional completeness? A set of operations is functionally complete if any Boolean function can be expressed using only those operations. {AND, OR, NOT} and {NAND} and {NOR} are each functionally complete.


Practice Problems

๐Ÿ“Practice: Boolean Simplification

Problem: Simplify F=AB+ABห‰+Aห‰B+Aห‰Bห‰F = AB + A\bar{B} + \bar{A}B + \bar{A}\bar{B}.

๐Ÿ’กSolution: Boolean Simplification

F=A(B+Bห‰)+Aห‰(B+Bห‰)=Aโ‹…1+Aห‰โ‹…1=A+Aห‰=1F = A(B + \bar{B}) + \bar{A}(B + \bar{B}) = A \cdot 1 + \bar{A} \cdot 1 = A + \bar{A} = 1. The function is always true (tautology).

๐Ÿ“Practice: Karnaugh Map

Problem: Simplify F(A,B,C)=โˆ‘m(0,1,2,5,6,7)F(A,B,C) = \sum m(0, 1, 2, 5, 6, 7) using a K-map.

๐Ÿ’กSolution: Karnaugh Map

K-map groups: Aห‰Bห‰\bar{A}\bar{B} (covers m0, m1), Aห‰C\bar{A}C (covers m1, m5), BB (covers m2, m6, m3, m7). Minimal SOP: F=Aห‰Bห‰+Aห‰C+BF = \bar{A}\bar{B} + \bar{A}C + B.

๐Ÿ“Practice: De Morgan's

Problem: Apply De Morgan's to (A+B)Cห‰โ€พ\overline{(A + B)\bar{C}}.

๐Ÿ’กSolution: De Morgan's

(A+B)Cห‰โ€พ=A+Bโ€พ+Cห‰โ€พ=Aห‰Bห‰+C\overline{(A + B)\bar{C}} = \overline{A + B} + \overline{\bar{C}} = \bar{A}\bar{B} + C.

๐Ÿ“Practice: Gate Implementation

Problem: Implement XOR using only AND, OR, and NOT gates.

๐Ÿ’กSolution: Gate Implementation

AโŠ•B=ABห‰+Aห‰BA \oplus B = A\bar{B} + \bar{A}B. Requires two NOT gates, two AND gates, and one OR gate.


Quick Reference

OperationSymbolTruth Table
ANDaโ‹…ba \cdot b1 only when both 1
ORa+ba + b1 when at least one 1
NOTaห‰\bar{a}Flips the value
XORaโŠ•ba \oplus b1 when different
NANDabโ€พ\overline{ab}NOT of AND
NORa+bโ€พ\overline{a+b}NOT of OR
XNORaโŠ•bโ€พ\overline{a \oplus b}1 when same
IdentityFormula
Idempotenta+a=aa + a = a, aโ‹…a=aa \cdot a = a
Complementa+aห‰=1a + \bar{a} = 1, aโ‹…aห‰=0a \cdot \bar{a} = 0
Absorptiona+ab=aa + ab = a, a(a+b)=aa(a+b) = a
De Morgan'sabโ€พ=aห‰+bห‰\overline{ab} = \bar{a}+\bar{b}, a+bโ€พ=aห‰bห‰\overline{a+b} = \bar{a}\bar{b}
Consensusab+aห‰c+bc=ab+aห‰cab + \bar{a}c + bc = ab + \bar{a}c

Quine-McCluskey Method

โ„น๏ธ Quine-McCluskey Method

The Quine-McCluskey method is a tabular algorithm for Boolean minimization, guaranteed to find the minimal form (unlike K-maps which are limited to 6 variables):

  1. Group minterms by number of 1s
  2. Combine terms that differ in exactly one position
  3. Mark combined terms as used
  4. Find prime implicants (terms that cannot be combined further)
  5. Use a prime implicant chart to select the minimal set covering all minterms
def quine_mccluskey(minterms, num_vars):
    def count_ones(n):
        return bin(n).count('1')

    def combine_terms(t1, t2):
        diff = 0
        pos = -1
        for i in range(num_vars):
            b1 = (t1 >> i) & 1
            b2 = (t2 >> i) & 1
            if b1 != b2:
                diff += 1
                pos = i
        if diff == 1:
            return t1 & ~(1 << pos)
        return None

    groups = {}
    for m in minterms:
        ones = count_ones(m)
        groups.setdefault(ones, []).append([m])

    prime_implicants = []
    while groups:
        new_groups = {}
        used = set()
        for g1 in sorted(groups.keys()):
            for g2 in sorted(groups.keys()):
                if g2 <= g1:
                    continue
                for t1 in groups[g1]:
                    for t2 in groups[g2]:
                        combined = combine_terms(t1[0], t2[0])
                        if combined is not None:
                            new_terms = sorted(set(t1 + t2))
                            key = tuple(new_terms)
                            if key not in new_groups:
                                new_groups[key] = [new_terms]
                            else:
                                new_groups[key].append(new_terms)
                            used.add(t1[0])
                            used.add(t2[0])

        for g in groups.values():
            for t in g:
                if t[0] not in used:
                    prime_implicants.append(t)

        if not new_groups:
            break
        groups = {}
        for key, terms in new_groups.items():
            ones = count_ones(key[0])
            groups.setdefault(ones, []).extend(terms)

    return prime_implicants

# Example: minimize F(A,B,C) = sum(1, 2, 3, 5, 7)
pis = quine_mccluskey([1, 2, 3, 5, 7], 3)
print(f"Prime implicants: {[bin(p[0]) for p in pis]}")

Boolean Function Properties

PropertyDescription
Self-dualf=fdf = f^d (function equals its dual)
MonotoneIncreasing any input never decreases output
Linearf=a0โŠ•a1x1โŠ•โ‹ฏโŠ•anxnf = a_0 \oplus a_1 x_1 \oplus \cdots \oplus a_n x_n
BalancedOutputs 0 and 1 equally often
AffineLinear plus a constant

Cross-References

Lesson Progress78 / 100