TExcelTAD
Home › Discrete Mathematics › Discrete Math Exercises

Discrete Math Exercises

Time to practise the whole course. Each exercise has a starter program that runs but doesn't do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.

Tip: Work a tiny case by hand first (three variables, a six-vertex graph, n=4n = 4), then let the code check the general case. A brute-force check over all small inputs is the discrete mathematician's best friend.

# Exercise Practises
1 Is the argument valid? truth tables, implication, validity
2 Modular inverses with Euclid extended Euclid, Bézout coefficients
3 Sieve of Eratosthenes primes, the prime number theorem
4 Fast modular exponentiation repeated squaring, binary expansion
5 Topological sort DAGs, in-degrees, scheduling
6 Is the graph bipartite? 2-coloring, BFS, odd cycles
7 Derangements inclusion-exclusion, brute-force check
8 Strings without "11" recurrences, Fibonacci

Exercise 1: Is the argument valid?

An argument "if P1P_1 and P2P_2 then CC" is valid when (P1∧P2)→C(P_1 \land P_2) \to C is true in every row of the truth table (Equivalence and Validity). Check two arguments: (a) from p→qp \to q and q→rq \to r conclude p→rp \to r; (b) from p→qp \to q and qq conclude pp. The starter's valid always says yes.

python · try it yourself
from itertools import product

implies = lambda a, b: (not a) or b

def valid(premises, conclusion, nvars):
    # TODO: return False if some assignment makes all premises true and the conclusion false
    return True

chain = valid([lambda p, q, r: implies(p, q), lambda p, q, r: implies(q, r)],
              lambda p, q, r: implies(p, r), 3)
converse = valid([lambda p, q: implies(p, q), lambda p, q: q], lambda p, q: p, 2)
print("chain rule valid:", chain)
print("affirming the consequent valid:", converse)
chain rule valid: True
affirming the consequent valid: True

Expected output when solved:

text
chain rule valid: True
affirming the consequent valid: False

The chain rule (hypothetical syllogism) is valid; "affirming the consequent" is a classic fallacy, refuted by the row pp false, qq true.

Hint: Loop over product([False, True], repeat=nvars) and test all(f(*v) for f in premises) and not conclusion(*v).

Solution
python · try it yourself
from itertools import product

implies = lambda a, b: (not a) or b

def valid(premises, conclusion, nvars):
    for v in product([False, True], repeat=nvars):
        if all(f(*v) for f in premises) and not conclusion(*v):
            return False
    return True

chain = valid([lambda p, q, r: implies(p, q), lambda p, q, r: implies(q, r)],
              lambda p, q, r: implies(p, r), 3)
converse = valid([lambda p, q: implies(p, q), lambda p, q: q], lambda p, q: p, 2)
print("chain rule valid:", chain)
print("affirming the consequent valid:", converse)
chain rule valid: True
affirming the consequent valid: False

Exercise 2: Modular inverses with Euclid

Write the extended Euclidean algorithm (GCD) returning (g,s,t)(g, s, t) with sa+tb=gsa + tb = g, then use it to find inverses modulo 101 (Modular Inverses). The starter returns dummy values.

python · try it yourself
def ext_gcd(a, b):
    # TODO: recursive extended Euclid: if b == 0 return (a, 1, 0)
    return (1, 0, 0)

def inverse(a, m):
    g, s, t = ext_gcd(a, m)
    return s % m if g == 1 else None

for a in [2, 7, 50, 100]:
    inv = inverse(a, 101)
    print(a, inv, (a * inv) % 101 if inv is not None else "-")
print(ext_gcd(240, 46))
2 0 0
7 0 0
50 0 0
100 0 0
(1, 0, 0)

Expected output when solved:

text
2 51 1
7 29 1
50 99 1
100 100 1
(2, -9, 47)

Each product a⋅a−1a \cdot a^{-1} is 1 modulo 101, and −9⋅240+47⋅46=2=gcd⁡(240,46)-9 \cdot 240 + 47 \cdot 46 = 2 = \gcd(240, 46).

Hint: If ext_gcd(b, a % b) returns (g, s, t), then (g, t, s - (a // b) * t) works for (a, b).

Solution
python · try it yourself
def ext_gcd(a, b):
    if b == 0:
        return (a, 1, 0)
    g, s, t = ext_gcd(b, a % b)
    return (g, t, s - (a // b) * t)

def inverse(a, m):
    g, s, t = ext_gcd(a, m)
    return s % m if g == 1 else None

for a in [2, 7, 50, 100]:
    inv = inverse(a, 101)
    print(a, inv, (a * inv) % 101 if inv is not None else "-")
print(ext_gcd(240, 46))
2 51 1
7 29 1
50 99 1
100 100 1
(2, -9, 47)

Exercise 3: Sieve of Eratosthenes

List the primes below NN by crossing out multiples (Primes), then compare the count π(N)\pi(N) with the estimate N/ln⁡NN / \ln N. The starter marks every number from 2 on as prime.

python · try it yourself
import math

def sieve(N):
    is_prime = [False, False] + [True] * (N - 2)
    # TODO: for each p with p * p < N that is still marked prime, cross out p*p, p*p+p, ...
    return [i for i in range(N) if is_prime[i]]

ps = sieve(100)
print(ps[:12])
for N in [100, 1000, 10000, 100000]:
    print(N, len(sieve(N)), round(N / math.log(N)))
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
100 98 22
1000 998 145
10000 9998 1086
100000 99998 8686

Expected output when solved:

text
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
100 25 22
1000 168 145
10000 1229 1086
100000 9592 8686

The ratio π(N)/(N/ln⁡N)\pi(N) / (N / \ln N) falls slowly toward 1, as the prime number theorem promises.

Hint: is_prime[p * p::p] = [False] * len(range(p * p, N, p)) crosses out a whole slice at once.

Solution
python · try it yourself
import math

def sieve(N):
    is_prime = [False, False] + [True] * (N - 2)
    p = 2
    while p * p < N:
        if is_prime[p]:
            is_prime[p * p::p] = [False] * len(range(p * p, N, p))
        p += 1
    return [i for i in range(N) if is_prime[i]]

ps = sieve(100)
print(ps[:12])
for N in [100, 1000, 10000, 100000]:
    print(N, len(sieve(N)), round(N / math.log(N)))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
100 25 22
1000 168 145
10000 1229 1086
100000 9592 8686

Exercise 4: Fast modular exponentiation

RSA needs ae mod na^e \bmod n for exponents with hundreds of digits (RSA). Repeated squaring reads ee in binary: square for every bit, multiply when the bit is 1, so it needs about 2log⁡2e2 \log_2 e multiplications. Count them. The starter multiplies ee times, which is hopeless for big ee, so it is only tried on a small one.

python · try it yourself
def power_mod(a, e, n):
    result, mults = 1, 0
    # TODO: replace this loop by repeated squaring
    for _ in range(e):
        result = result * a % n
        mults += 1
    return result, mults

print(power_mod(7, 1000, 13), pow(7, 1000, 13))
e = 2 ** 64 + 12345
print("big exponent: skipped")   # TODO: print(power_mod(5, e, 1000003), pow(5, e, 1000003))
(9, 1000) 9
big exponent: skipped

Expected output when solved:

text
(9, 16) 9
(795388, 72) 795388

Hint: While e > 0: if e & 1, multiply result by a; then square a and shift e >>= 1. Count both kinds of multiplication.

Solution
python · try it yourself
def power_mod(a, e, n):
    result, mults = 1, 0
    a %= n
    while e > 0:
        if e & 1:
            result = result * a % n
            mults += 1
        a = a * a % n
        mults += 1
        e >>= 1
    return result, mults

print(power_mod(7, 1000, 13), pow(7, 1000, 13))
e = 2 ** 64 + 12345
print(power_mod(5, e, 1000003), pow(5, e, 1000003))
(9, 16) 9
(795388, 72) 795388

Exercise 5: Topological sort

Order the tasks of a small build so that every task comes after its prerequisites (DAGs and Scheduling). Kahn's algorithm repeatedly takes a task with no unfinished prerequisites. Use the alphabetically first available task each time so the answer is unique. The starter just sorts the names.

python · try it yourself
import heapq

deps = {                       # task: prerequisites
    "compile": ["fetch", "configure"],
    "configure": ["fetch"],
    "docs": ["compile"],
    "fetch": [],
    "link": ["compile"],
    "package": ["link", "docs", "test"],
    "test": ["link"],
}

def topo_order(deps):
    # TODO: Kahn's algorithm with a heap of ready tasks (in-degree 0)
    return sorted(deps)

order = topo_order(deps)
print(order)
pos = {t: i for i, t in enumerate(order)}
print("valid:", all(pos[p] < pos[t] for t in deps for p in deps[t]))
['compile', 'configure', 'docs', 'fetch', 'link', 'package', 'test']
valid: False

Expected output when solved:

text
['fetch', 'configure', 'compile', 'docs', 'link', 'test', 'package']
valid: True

Hint: Count unfinished prerequisites per task, push the tasks with count 0 onto a heap, and when you pop a task, decrease the count of every task that depends on it.

Solution
python · try it yourself
import heapq

deps = {                       # task: prerequisites
    "compile": ["fetch", "configure"],
    "configure": ["fetch"],
    "docs": ["compile"],
    "fetch": [],
    "link": ["compile"],
    "package": ["link", "docs", "test"],
    "test": ["link"],
}

def topo_order(deps):
    remaining = {t: len(ps) for t, ps in deps.items()}
    users = {t: [] for t in deps}
    for t, ps in deps.items():
        for p in ps:
            users[p].append(t)
    ready = [t for t, k in remaining.items() if k == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        t = heapq.heappop(ready)
        order.append(t)
        for u in users[t]:
            remaining[u] -= 1
            if remaining[u] == 0:
                heapq.heappush(ready, u)
    return order if len(order) == len(deps) else None   # None means a cycle

order = topo_order(deps)
print(order)
pos = {t: i for i, t in enumerate(order)}
print("valid:", all(pos[p] < pos[t] for t in deps for p in deps[t]))
['fetch', 'configure', 'compile', 'docs', 'link', 'test', 'package']
valid: True

Exercise 6: Is the graph bipartite?

A graph is bipartite exactly when it has no odd cycle, and breadth-first search finds a 2-coloring or proves none exists (Graph Coloring). Test a 6-cycle, a 5-cycle and a 3×33 \times 3 grid graph. The starter answers yes every time.

python · try it yourself
from collections import deque

def cycle(n):
    return {i: [(i - 1) % n, (i + 1) % n] for i in range(n)}

def grid(k):
    g = {(r, c): [] for r in range(k) for c in range(k)}
    for r, c in g:
        for dr, dc in [(1, 0), (0, 1)]:
            if (r + dr, c + dc) in g:
                g[(r, c)].append((r + dr, c + dc))
                g[(r + dr, c + dc)].append((r, c))
    return g

def two_color(g):
    color = {}
    # TODO: BFS from every uncolored vertex; give neighbours the opposite color;
    #       return None if an edge joins two vertices of the same color
    return color

for name, g in [("C6", cycle(6)), ("C5", cycle(5)), ("grid 3x3", grid(3))]:
    col = two_color(g)
    print(name, "bipartite" if col is not None else "not bipartite",
          "" if col is None else sum(col.values()))
C6 bipartite 0
C5 bipartite 0
grid 3x3 bipartite 0

Expected output when solved:

text
C6 bipartite 3
C5 not bipartite
grid 3x3 bipartite 4

The last number is how many vertices got color 1: half of C6C_6, and 4 of the 9 grid cells (the cells with r+cr + c odd).

Hint: Start each BFS with color[s] = 0; for an edge u -> v, set color[v] = 1 - color[u] if v is new, and fail if color[v] == color[u].

Solution
python · try it yourself
from collections import deque

def cycle(n):
    return {i: [(i - 1) % n, (i + 1) % n] for i in range(n)}

def grid(k):
    g = {(r, c): [] for r in range(k) for c in range(k)}
    for r, c in g:
        for dr, dc in [(1, 0), (0, 1)]:
            if (r + dr, c + dc) in g:
                g[(r, c)].append((r + dr, c + dc))
                g[(r + dr, c + dc)].append((r, c))
    return g

def two_color(g):
    color = {}
    for s in g:
        if s in color:
            continue
        color[s] = 0
        queue = deque([s])
        while queue:
            u = queue.popleft()
            for v in g[u]:
                if v not in color:
                    color[v] = 1 - color[u]
                    queue.append(v)
                elif color[v] == color[u]:
                    return None
    return color

for name, g in [("C6", cycle(6)), ("C5", cycle(5)), ("grid 3x3", grid(3))]:
    col = two_color(g)
    print(name, "bipartite" if col is not None else "not bipartite",
          "" if col is None else sum(col.values()))
C6 bipartite 3
C5 not bipartite
grid 3x3 bipartite 4

Exercise 7: Derangements

A derangement is a permutation with no fixed point: nobody gets their own hat back. By inclusion-exclusion,

Dn=∑k=0n(−1)k(nk)(n−k)!D_n = \sum_{k=0}^{n} (-1)^k \binom{n}{k} (n-k)!

Implement the formula, check it by brute force for small nn, and watch Dn/n!D_n / n! approach 1/e1/e. The starter's formula keeps only the k=0k = 0 term.

python · try it yourself
import math
from itertools import permutations

def derangements(n):
    # TODO: sum over k = 0..n of (-1)**k * comb(n, k) * factorial(n - k)
    return math.factorial(n)

def brute(n):
    return sum(1 for p in permutations(range(n)) if all(p[i] != i for i in range(n)))

print([derangements(n) for n in range(1, 8)])
print([brute(n) for n in range(1, 8)])
print(round(derangements(12) / math.factorial(12), 8), round(1 / math.e, 8))
[1, 2, 6, 24, 120, 720, 5040]
[0, 1, 2, 9, 44, 265, 1854]
1.0 0.36787944

Expected output when solved:

text
[0, 1, 2, 9, 44, 265, 1854]
[0, 1, 2, 9, 44, 265, 1854]
0.36787944 0.36787944

Hint: sum((-1) ** k * math.comb(n, k) * math.factorial(n - k) for k in range(n + 1)).

Solution
python · try it yourself
import math
from itertools import permutations

def derangements(n):
    return sum((-1) ** k * math.comb(n, k) * math.factorial(n - k) for k in range(n + 1))

def brute(n):
    return sum(1 for p in permutations(range(n)) if all(p[i] != i for i in range(n)))

print([derangements(n) for n in range(1, 8)])
print([brute(n) for n in range(1, 8)])
print(round(derangements(12) / math.factorial(12), 8), round(1 / math.e, 8))
[0, 1, 2, 9, 44, 265, 1854]
[0, 1, 2, 9, 44, 265, 1854]
0.36787944 0.36787944

Exercise 8: Strings without "11"

Count the binary strings of length nn with no two adjacent 1s. Split on the first character: a string starting with 0 continues with any valid string of length n−1n - 1; one starting with 1 must continue with 0 and then any valid string of length n−2n - 2. So an=an−1+an−2a_n = a_{n-1} + a_{n-2} with a1=2a_1 = 2, a2=3a_2 = 3 (Recurrences). The starter only has the brute-force count.

python · try it yourself
from itertools import product

def brute(n):
    return sum(1 for s in product("01", repeat=n) if "11" not in "".join(s))

def by_recurrence(n):
    # TODO: iterate a_n = a_(n-1) + a_(n-2) from a_1 = 2, a_2 = 3
    return 0

print([brute(n) for n in range(1, 13)])
print([by_recurrence(n) for n in range(1, 13)])
print(by_recurrence(80))
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
0

Expected output when solved:

text
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
61305790721611591

These are Fibonacci numbers shifted by two places, an=Fn+2a_n = F_{n+2}, and the recurrence handles n=80n = 80, where brute force would need 2802^{80} strings.

Hint: Keep two variables a, b = 2, 3 and step a, b = b, a + b.

Solution
python · try it yourself
from itertools import product

def brute(n):
    return sum(1 for s in product("01", repeat=n) if "11" not in "".join(s))

def by_recurrence(n):
    a, b = 2, 3
    for _ in range(n - 1):
        a, b = b, a + b
    return a

print([brute(n) for n in range(1, 13)])
print([by_recurrence(n) for n in range(1, 13)])
print(by_recurrence(80))
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
61305790721611591

Test yourself

Which assignment refutes "from p→qp \to q and qq, conclude pp"?

  1. pp true, qq true
  2. pp false, qq true
  3. pp true, qq false
  4. pp false, qq false

About how many multiplications does repeated squaring need for an exponent near 2642^{64}?

  1. About 64 to 128
  2. About 2^32
  3. About 2^64
  4. Exactly 64 squared

A graph has no 2-coloring exactly when it contains…

  1. a vertex of degree 3
  2. a cycle of odd length
  3. a cycle of even length
  4. more edges than vertices

Where next

You have used every chapter of the course: logic, number theory, graphs, counting and recurrences. The Mini Project combines DAGs, coloring and counting in one program. For the probability side, continue with Probability Theory; for algorithms built on these ideas, see the DSA course.