About

Midterm Exam Solutions (Q1–Q7)

Midterm Exam Questions & Solutions

This module contains the complete set of questions from the midterm examination, presented in interactive exercise cards with step-by-step solutions.


Section 1: Prime Numbers

Exercise 1.1

(2 points) Define what is a prime number.

Show solution ↓
Solution

A prime number is an integer strictly greater than 1 that has exactly two positive divisors: 1 and itself.

P={2,3,5,7,11,13,17,19,23,29,31,… }P = \{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, \dots\}

An integer greater than 1 with three or more positive divisors is a composite number. The number 1 is neither prime nor composite.

Exercise 1.2.1

(6 points) Given an integer nn, write a brute-force algorithm to list all primes between 2 and nn according to the definition of a prime number. State its time complexity.

Show solution ↓
Solution

Test each integer pp from 22 to nn against all potential divisors i∈[2,p−1]i \in [2, p - 1]:

BruteForcePrimes(n):
    // Input: Integer n >= 2
    // Output: List L of prime numbers <= n
    L = empty list
    for p = 2 to n do:
        isPrime = 1
        for i = 2 to p - 1 do:
            if p mod i == 0 then:
                isPrime = 0
                break
        if isPrime == 1 then:
            L.append(p)
    return L
  • Time Complexity: Θ(n2)\Theta(n^2) because in the worst case (when pp is prime), the inner loop runs p−2p - 2 times: ∑p=2n(p−2)=(n−2)(n−1)2=Θ(n2)\sum_{p=2}^n (p - 2) = \frac{(n-2)(n-1)}{2} = \Theta(n^2)
  • Square-Root Optimization: Only testing divisors up to ⌊p⌋\lfloor \sqrt{p} \rfloor improves running time to Θ(nn)\Theta(n \sqrt{n}):
    for i = 2 to floor(sqrt(p)) do:
        if p mod i == 0 then:
            isPrime = 0
            break
Exercise 1.2.2

(6 points) Given an integer nn, write an algorithm to list all primes between 2 and nn using the Sieve of Eratosthenes. State its time and space complexity.

Show solution ↓
Solution
SieveOfEratosthenes(n):
    // Input: Integer n >= 2
    // Output: List L of prime numbers <= n
    create array A[2..n]
    for p = 2 to n do A[p] = p

    for p = 2 to floor(sqrt(n)) do:
        if A[p] != 0 then:
            j = p * p
            while j <= n do:
                A[j] = 0
                j = j + p

    L = empty list
    for p = 2 to n do:
        if A[p] != 0 then:
            L.append(A[p])
    return L
  • Why start crossing out at p2p^2? Any composite multiple k⋅pk \cdot p where k<pk < p has already been crossed out when processing the smaller prime factor of kk.
  • Time Complexity: Θ(nlog⁡log⁡n)\Theta(n \log \log n).
  • Space Complexity: Θ(n)\Theta(n) for array A[2..n]A[2..n].

Section 2: Find the Big-Θ\Theta for the Following Seven Algorithms (1 point each)

Exercise 2.1
for (int sum = 0, i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++)
        sum++;
}
Show solution ↓
Solution

The outer loop runs for i=1,2,…,ni = 1, 2, \dots, n. For each ii, the inner loop executes ii times:

∑i=1n∑j=1i1=∑i=1ni=n(n+1)2=Θ(n2)\sum_{i=1}^n \sum_{j=1}^i 1 = \sum_{i=1}^n i = \frac{n(n + 1)}{2} = \Theta(n^2)

Answer: Θ(n2)\mathbf{\Theta(n^2)}

Exercise 2.2
for (count = 0, i = 0; i < n; i++) {
    for (j = i + 1; j < n; j++) {
        for (k = j + 1; k < n; k++) {
            count++;
        }
    }
}
Show solution ↓
Solution

The three indices satisfy 0≤i<j<k<n0 \le i < j < k < n, so count++ executes exactly once per unordered triple drawn from nn values:

(n3)=n(n−1)(n−2)6=Θ(n3)\binom{n}{3} = \frac{n(n-1)(n-2)}{6} = \Theta(n^3)

Answer: Θ(n3)\mathbf{\Theta(n^3)}

Exercise 2.3
for (count = 0, i = 0; i < n; i++) {
    for (j = i + 1; j < n * n; j++) {
        count++;
    }
}
Show solution ↓
Solution
  • The outer loop executes nn times (i=0i = 0 to n−1n - 1).
  • The inner loop has an upper bound of n2n^2, running n2−(i+1)≈n2n^2 - (i + 1) \approx n^2 times for each ii:
∑i=0n−1(n2−i−1)≈n⋅n2=Θ(n3)\sum_{i=0}^{n-1} (n^2 - i - 1) \approx n \cdot n^2 = \Theta(n^3)

Answer: Θ(n3)\mathbf{\Theta(n^3)}

Exercise 2.4
for (count = 0, i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
        count++;
    }

    for (k = 0; k < n; k++) {
        for (j = 2; j <= n; j = j * j) {
            count++;
        }
    }

    for (m = 0; m < n; m++) {
        count++;
    }
}
Show solution ↓
Solution

Examine each inner block inside the outer loop ii:

  1. for (j = 0; j < n; j++): executes nn times   ⟹  Θ(n)\implies \Theta(n).
  2. for (j = 2; j <= n; j = j * j): jj squares at each step: 2,4,16,256,…,22t≤n  ⟹  t≤log⁡2(log⁡2n)2, 4, 16, 256, \dots, 2^{2^t} \le n \implies t \le \log_2(\log_2 n). This inner loop executes Θ(log⁡log⁡n)\Theta(\log \log n) times. Enclosed in loop kk running nn times: n×Θ(log⁡log⁡n)=Θ(nlog⁡log⁡n)n \times \Theta(\log \log n) = \Theta(n \log \log n).
  3. for (m = 0; m < n; m++): executes nn times   ⟹  Θ(n)\implies \Theta(n).

Total work inside outer loop ii:

Θ(n)+Θ(nlog⁡log⁡n)+Θ(n)=Θ(nlog⁡log⁡n)\Theta(n) + \Theta(n \log \log n) + \Theta(n) = \Theta(n \log \log n)

Multiplied by outer loop ii running nn times:

n×Θ(nlog⁡log⁡n)=Θ(n2log⁡log⁡n)n \times \Theta(n \log \log n) = \mathbf{\Theta(n^2 \log \log n)}

(Note: If the inner step is multiplicative j←j×5j \leftarrow j \times 5, it executes in Θ(log⁡n)\Theta(\log n) steps, yielding Θ(n2log⁡n)\mathbf{\Theta(n^2 \log n)}).

Answer: Θ(n2log⁡log⁡n)\mathbf{\Theta(n^2 \log \log n)} (or Θ(n2log⁡n)\mathbf{\Theta(n^2 \log n)})

Exercise 2.5
for (count = 0, i = 0; i < n; i++) {
    for (j = 2; j <= 7; j++) {
        count++;
    }
}
Show solution ↓
Solution

The inner loop bound is constant: jj iterates from 22 to 77, which is exactly 66 operations regardless of nn:

∑i=0n−16=6n=Θ(n)\sum_{i=0}^{n-1} 6 = 6n = \Theta(n)

Answer: Θ(n)\mathbf{\Theta(n)}

Exercise 2.6
for (count = 0, i = 0; i < n; i++) {
    if (i < sqrt(n)) {
        for (j = 0; j < n; j++) {
            count++;
        }
    } else {
        for (k = 0; k < n; k++) {
            count++;
        }
    }
}
Show solution ↓
Solution

For every single iteration of the outer loop ii, either the if branch or the else branch is taken. Both branches contain a loop running from 00 to n−1n-1, which executes exactly nn operations:

Work per iteration of i=Θ(n)\text{Work per iteration of } i = \Theta(n)

Total operations across all nn outer iterations:

n×Θ(n)=Θ(n2)n \times \Theta(n) = \Theta(n^2)

Answer: Θ(n2)\mathbf{\Theta(n^2)}

Exercise 2.7
for (int sum = 0, i = 1; i <= n; i++) {
    for (int j = n; j >= 1; j = j / 2) {
        sum++;
    }
}
Show solution ↓
Solution

The inner loop repeatedly halves jj: n,n/2,n/4,…,1n, n/2, n/4, \dots, 1. The number of divisions until j<1j < 1 is ⌊log⁡2n⌋+1=Θ(log⁡n)\lfloor \log_2 n \rfloor + 1 = \Theta(\log n). Outer loop runs nn times:

∑i=1nΘ(log⁡n)=n⋅Θ(log⁡n)=Θ(nlog⁡n)\sum_{i=1}^n \Theta(\log n) = n \cdot \Theta(\log n) = \Theta(n \log n)

Answer: Θ(nlog⁡n)\mathbf{\Theta(n \log n)}


Section 3: Tower of Hanoi

Exercise 3.1

(2 points) Define the Tower of Hanoi problem (hint: Goal and Constraints).

Show solution ↓
Solution

The Tower of Hanoi consists of three pegs (Source, Auxiliary, Destination) and nn disks of distinct sizes initially stacked on the source peg in decreasing order of size.

  • Goal: Transfer all nn disks from the source peg to the destination peg.
  • Constraints:
    1. Only one disk may be moved at a time.
    2. Only the top disk on any peg can be moved.
    3. No larger disk may be placed on top of a smaller disk.
Exercise 3.2

(6 points) Show the work of the algorithm step-by-step for the Tower of Hanoi problem where n=4n = 4.

Show solution ↓
Solution

For n=4n = 4, the minimum number of moves is 24−1=152^4 - 1 = 15 moves. Let Peg 1 be Source, Peg 2 be Auxiliary, and Peg 3 be Destination:

Move #Disk MovedPeg ActionPeg 1 (Source)Peg 2 (Aux)Peg 3 (Dest)
Start-Initial[4,3,2,1][4, 3, 2, 1][][][][]
1Disk 11→21 \to 2[4,3,2][4, 3, 2][1][1][][]
2Disk 21→31 \to 3[4,3][4, 3][1][1][2][2]
3Disk 12→32 \to 3[4,3][4, 3][][][2,1][2, 1]
4Disk 31→21 \to 2[4][4][3][3][2,1][2, 1]
5Disk 13→13 \to 1[4,1][4, 1][3][3][2][2]
6Disk 23→23 \to 2[4,1][4, 1][3,2][3, 2][][]
7Disk 11→21 \to 2[4][4][3,2,1][3, 2, 1][][]
8Disk 41→3\mathbf{1 \to 3}[][][3,2,1][3, 2, 1][4][4]
9Disk 12→32 \to 3[][][3,2][3, 2][4,1][4, 1]
10Disk 22→12 \to 1[2][2][3][3][4,1][4, 1]
11Disk 13→13 \to 1[2,1][2, 1][3][3][4][4]
12Disk 32→32 \to 3[2,1][2, 1][][][4,3][4, 3]
13Disk 11→21 \to 2[2][2][1][1][4,3][4, 3]
14Disk 21→31 \to 3[][][1][1][4,3,2][4, 3, 2]
15Disk 12→32 \to 3[][][][][4,3,2,1][4, 3, 2, 1]

Final state: all 4 disks are stacked correctly on Destination Peg 3.

Exercise 3.3

(5 points) Write a recursive algorithm to solve the Tower of Hanoi problem for the minimum number of moves. Give its recurrence and complexity.

Show solution ↓
Solution
Hanoi(n, source, destination, auxiliary):
    if n == 1 then:
        move disk 1 from source to destination
        return

    Hanoi(n - 1, source, auxiliary, destination)
    move disk n from source to destination
    Hanoi(n - 1, auxiliary, destination, source)
  • Recurrence Relation: T(n)=2T(n−1)+1for n>1,T(1)=1T(n) = 2T(n - 1) + 1 \quad \text{for } n > 1, \quad T(1) = 1
  • Closed Form: T(n)=2n−1T(n) = 2^n - 1 moves.
  • Time Complexity: Θ(2n)\Theta(2^n).
  • Space Complexity: Θ(n)\Theta(n) (maximum recursion call stack depth).

Section 4: Brute-Force Pattern Matching

Exercise 4.1

(5 points) Write a brute-force algorithm to search for pattern PP in text TT. State its best-case and worst-case time complexities.

Show solution ↓
Solution

Let text TT have length nn and pattern PP have length m≤nm \le n:

BruteForceSearch(T, P):
    n = length(T)
    m = length(P)
    for i = 0 to n - m do:
        j = 0
        while j < m and T[i + j] == P[j] do:
            j = j + 1
        if j == m return i
    return -1
  • Worst-Case Time Complexity: Θ(n⋅m)\Theta(n \cdot m) (e.g., T="AAAAAAAAAB"T = \text{"AAAAAAAAAB"}, P="AAB"P = \text{"AAB"}).
  • Best-Case Time Complexity: Θ(n)\Theta(n) (when the first character of PP immediately mismatches).
  • Space Complexity: Θ(1)\Theta(1) auxiliary space.
Exercise 4.2

(7 points) Board DD stores characters in a 2-dimensional array. Pattern PP could be read horizontally (left-to-right) or vertically (top-to-bottom). Write a brute-force algorithm to search for pattern PP in board DD, and state its time complexity.

Show solution ↓
Solution

Let board DD have RR rows and CC columns, and pattern PP have length mm:

function search2D(board, P) {
    const R = board.length;
    const C = board[0].length;
    const m = P.length;

    for (let r = 0; r < R; r++) {
        for (let c = 0; c < C; c++) {
            // 1. Horizontal Search (Left to Right)
            if (c + m <= C) {
                let j = 0;
                while (j < m && board[r][c + j] === P[j]) {
                    j++;
                }
                if (j === m) console.log(`Found horizontally at (${r}, ${c})`);
            }

            // 2. Vertical Search (Top to Bottom)
            if (r + m <= R) {
                let j = 0;
                while (j < m && board[r + j][c] === P[j]) {
                    j++;
                }
                if (j === m) console.log(`Found vertically at (${r}, ${c})`);
            }
        }
    }
}
  • Time Complexity: For an R×CR \times C board, each of the R⋅CR \cdot C cells performs at most 2m2m comparisons, giving Θ(R⋅C⋅m)\mathbf{\Theta(R \cdot C \cdot m)}.
  • For an n×nn \times n square board, the complexity is Θ(n2⋅m)\mathbf{\Theta(n^2 \cdot m)}.

Exercise 5

(7 points) Using exhaustive search to solve the assignment problem below. Find the minimum-cost assignment and state the time complexity.

PersonJob 1Job 2Job 3Job 4
Person A51143
Person B61038
Person C7946
Person D101269
Show solution ↓
Solution

Each person must be assigned to exactly one job, and each job assigned to exactly one person. Exhaustive search enumerates all 4!=244! = 24 permutations and keeps the cheapest.

Minimum-cost assignment:

J1→B (6),J2→C (9),J3→D (6),J4→A (3)J_1 \to B\,(6), \quad J_2 \to C\,(9), \quad J_3 \to D\,(6), \quad J_4 \to A\,(3)Cost=6+9+6+3=24\text{Cost} = 6 + 9 + 6 + 3 = \mathbf{24}

This is the unique optimum. Two runner-up permutations cost 2525 and are the ones most often stopped at when the enumeration tree is pruned by eye rather than completed:

  1. A→J4(3)+B→J3(3)+C→J2(9)+D→J1(10)=25A \to J_4 (3) + B \to J_3 (3) + C \to J_2 (9) + D \to J_1 (10) = 25
  2. A→J4(3)+B→J3(3)+C→J1(7)+D→J2(12)=25A \to J_4 (3) + B \to J_3 (3) + C \to J_1 (7) + D \to J_2 (12) = 25

Both fix A→J4A \to J_4 and B→J3B \to J_3 because those are each row’s cheapest cell, but the greedy row-wise choice is not optimal here: paying 66 instead of 33 for BB frees J3J_3 for DD, whose alternatives are all far more expensive.

Time Complexity: Generating and evaluating all permutations takes Θ(n!)\mathbf{\Theta(n!)}.


Section 6: Closest Pair Problem

Exercise 6.1

(6 points) Write a brute-force algorithm to solve the closest pair problem. State its time complexity.

Show solution ↓
Solution
ClosestPairBruteForce(P):
    // Input: Array P of n points (x_i, y_i)
    // Output: Indices of closest pair and distance
    dmin = infinity
    index1 = null; index2 = null

    for i = 0 to n - 2 do:
        for j = i + 1 to n - 1 do:
            d = sqrt((P[i].x - P[j].x)^2 + (P[i].y - P[j].y)^2)
            if d < dmin then:
                dmin = d
                index1 = i
                index2 = j

    return index1, index2, dmin
  • Time Complexity: Computes Euclidean distance for all n(n−1)2\frac{n(n - 1)}{2} pairs   ⟹  Θ(n2)\implies \mathbf{\Theta(n^2)}.
  • Space Complexity: Θ(1)\Theta(1) auxiliary space.
Exercise 6.2

(5 points) How does the divide-and-conquer technique solve the closest pair problem? Elaborate your answer and state its time complexity.

Show solution ↓
Solution
  1. Step 1 (Divide): Sort all points by xx-coordinate. Divide the set into two equal subsets PLP_L and PRP_R using a vertical line x=mx = m.
  2. Step 2 (Conquer): Recursively compute the minimum pairwise distance in the left half (dLd_L) and right half (dRd_R). Set d=min⁡(dL,dR)d = \min(d_L, d_R).
  3. Step 3 (Combine): Check for points spanning across the dividing line:
    • Construct a vertical strip of width 2d2d (m−d≤x≤m+dm - d \le x \le m + d).
    • Sort the strip points by yy-coordinate.
    • For each point in the strip, inspect only subsequent points whose yy-difference is strictly less than dd. Geometrically, at most 6 points can fit in this region without violating the minimum distance condition.
  4. Recurrence & Complexity: T(n)=2T(n/2)+Θ(n)T(n) = 2T(n / 2) + \Theta(n) By the Master Theorem, the time complexity is Θ(nlog⁡n)\mathbf{\Theta(n \log n)}, improving upon the Θ(n2)\Theta(n^2) brute-force approach.

Section 7: Multiplication of Large Integers

Exercise 7.1

(8 points) Given the formula for multiplication of two large integers:

C=A×B=(a1⋅10m+a0)(b1⋅10m+b0)=c2⋅102m+c1⋅10m+c0C = A \times B = (a_1 \cdot 10^m + a_0)(b_1 \cdot 10^m + b_0) = c_2 \cdot 10^{2m} + c_1 \cdot 10^m + c_0

where c2=a1b1c_2 = a_1 b_1, c0=a0b0c_0 = a_0 b_0, and c1=(a1+a0)(b1+b0)−c2−c0c_1 = (a_1 + a_0)(b_1 + b_0) - c_2 - c_0. Compute 2134×56872134 \times 5687 using this divide-and-conquer technique.

Show solution ↓
Solution

Let m=2m = 2:

  • A=2134  ⟹  a1=21, a0=34A = 2134 \implies a_1 = 21, \ a_0 = 34
  • B=5687  ⟹  b1=56, b0=87B = 5687 \implies b_1 = 56, \ b_0 = 87

Step 1: Compute c2c_2

c2=a1×b1=21×56=1176c_2 = a_1 \times b_1 = 21 \times 56 = 1176

Step 2: Compute c0c_0

c0=a0×b0=34×87=2958c_0 = a_0 \times b_0 = 34 \times 87 = 2958

Step 3: Compute c1c_1

(a1+a0)=21+34=55(b1+b0)=56+87=143(a1+a0)(b1+b0)=55×143=7865c1=7865−c2−c0=7865−1176−2958=3731\begin{aligned} (a_1 + a_0) &= 21 + 34 = 55 \\ (b_1 + b_0) &= 56 + 87 = 143 \\ (a_1 + a_0)(b_1 + b_0) &= 55 \times 143 = 7865 \\ c_1 &= 7865 - c_2 - c_0 = 7865 - 1176 - 2958 = 3731 \end{aligned}

Step 4: Combine the Results

A×B=c2⋅104+c1⋅102+c0=1176×104+3731×102+2958=11,760,000+373,100+2,958=12,136,058\begin{aligned} A \times B &= c_2 \cdot 10^4 + c_1 \cdot 10^2 + c_0 \\ &= 1176 \times 10^4 + 3731 \times 10^2 + 2958 \\ &= 11{,}760{,}000 + 373{,}100 + 2{,}958 \\ &= \mathbf{12{,}136{,}058} \end{aligned}
Exercise 7.2

(3 points) How is the divide-and-conquer technique applied to the given formula? How is the problem divided? How many subproblems are there? State the recurrence and time complexity.

Show solution ↓
Solution
  1. Division into Subproblems: The integers of nn digits are divided into high and low halves of n/2n/2 digits (a1,a0a_1, a_0 and b1,b0b_1, b_0).
  2. Number of Subproblems: Traditional multiplication requires 4 subproblems (a1b1,a1b0,a0b1,a0b0a_1 b_1, a_1 b_0, a_0 b_1, a_0 b_0). Karatsuba’s formula computes c1c_1 using only one additional product (a1+a0)(b1+b0)(a_1 + a_0)(b_1 + b_0) and linear additions/subtractions, reducing the count to 3 recursive subproblems.
  3. Recurrence Relation: T(n)=3T(n/2)+Θ(n)T(n) = 3T(n / 2) + \Theta(n)
  4. Time Complexity: By the Master Theorem (a=3,b=2,d=1a = 3, b = 2, d = 1, since a>bd=21a > b^d = 2^1): T(n)∈Θ(nlog⁡23)≈Θ(n1.585)T(n) \in \Theta(n^{\log_2 3}) \approx \mathbf{\Theta(n^{1.585})} This is asymptotically superior to the Θ(n2)\Theta(n^2) pencil-and-paper algorithm.