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 ↓Hide 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,…}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 n, write a brute-force algorithm to list all primes between 2 and n according to the definition of a prime number. State its time complexity.
Show solution ↓Hide solution ↑
Solution
Test each integer p from 2 to n against all potential divisors i∈[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
Exercise 1.2.2
(6 points) Given an integer n, write an algorithm to list all primes between 2 and n using the Sieve of Eratosthenes. State its time and space complexity.
Show solution ↓Hide 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 p2? Any composite multiple k⋅p where k<p has already been crossed out when processing the smaller prime factor of k.
- Time Complexity: Θ(nloglogn).
- Space Complexity: Θ(n) for array A[2..n].
Section 2: Find the Big-Θ 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 ↓Hide solution ↑
Solution
The outer loop runs for i=1,2,…,n. For each i, the inner loop executes i times:
i=1∑nj=1∑i1=i=1∑ni=2n(n+1)=Θ(n2)Answer: Θ(n2)
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 ↓Hide solution ↑
Solution
The three indices satisfy 0≤i<j<k<n, so count++ executes exactly once per
unordered triple drawn from n values:
(3n)=6n(n−1)(n−2)=Θ(n3)Answer: Θ(n3)
Exercise 2.3
for (count = 0, i = 0; i < n; i++) {
for (j = i + 1; j < n * n; j++) {
count++;
}
}
Show solution ↓Hide solution ↑
Solution
- The outer loop executes n times (i=0 to n−1).
- The inner loop has an upper bound of n2, running n2−(i+1)≈n2 times for each i:
i=0∑n−1(n2−i−1)≈n⋅n2=Θ(n3)Answer: Θ(n3)
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 ↓Hide solution ↑
Solution
Examine each inner block inside the outer loop i:
for (j = 0; j < n; j++): executes n times ⟹Θ(n).
for (j = 2; j <= n; j = j * j):
j squares at each step: 2,4,16,256,…,22t≤n⟹t≤log2(log2n).
This inner loop executes Θ(loglogn) times.
Enclosed in loop k running n times: n×Θ(loglogn)=Θ(nloglogn).
for (m = 0; m < n; m++): executes n times ⟹Θ(n).
Total work inside outer loop i:
Θ(n)+Θ(nloglogn)+Θ(n)=Θ(nloglogn)Multiplied by outer loop i running n times:
n×Θ(nloglogn)=Θ(n2loglogn)(Note: If the inner step is multiplicative j←j×5, it executes in Θ(logn) steps, yielding Θ(n2logn)).
Answer: Θ(n2loglogn) (or Θ(n2logn))
Exercise 2.5
for (count = 0, i = 0; i < n; i++) {
for (j = 2; j <= 7; j++) {
count++;
}
}
Show solution ↓Hide solution ↑
Solution
The inner loop bound is constant: j iterates from 2 to 7, which is exactly 6 operations regardless of n:
i=0∑n−16=6n=Θ(n)Answer: Θ(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 ↓Hide solution ↑
Solution
For every single iteration of the outer loop i, either the if branch or the else branch is taken. Both branches contain a loop running from 0 to n−1, which executes exactly n operations:
Work per iteration of i=Θ(n)Total operations across all n outer iterations:
n×Θ(n)=Θ(n2)Answer: Θ(n2)
Exercise 2.7
for (int sum = 0, i = 1; i <= n; i++) {
for (int j = n; j >= 1; j = j / 2) {
sum++;
}
}
Show solution ↓Hide solution ↑
Solution
The inner loop repeatedly halves j: n,n/2,n/4,…,1.
The number of divisions until j<1 is ⌊log2n⌋+1=Θ(logn).
Outer loop runs n times:
i=1∑nΘ(logn)=n⋅Θ(logn)=Θ(nlogn)Answer: Θ(nlogn)
Section 3: Tower of Hanoi
Exercise 3.1
(2 points) Define the Tower of Hanoi problem (hint: Goal and Constraints).
Show solution ↓Hide solution ↑
Solution
The Tower of Hanoi consists of three pegs (Source, Auxiliary, Destination) and n disks of distinct sizes initially stacked on the source peg in decreasing order of size.
- Goal: Transfer all n disks from the source peg to the destination peg.
- Constraints:
- Only one disk may be moved at a time.
- Only the top disk on any peg can be moved.
- 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=4.
Show solution ↓Hide solution ↑
Solution
For n=4, the minimum number of moves is 24−1=15 moves.
Let Peg 1 be Source, Peg 2 be Auxiliary, and Peg 3 be Destination:
| Move # | Disk Moved | Peg Action | Peg 1 (Source) | Peg 2 (Aux) | Peg 3 (Dest) |
|---|
| Start | - | Initial | [4,3,2,1] | [] | [] |
| 1 | Disk 1 | 1→2 | [4,3,2] | [1] | [] |
| 2 | Disk 2 | 1→3 | [4,3] | [1] | [2] |
| 3 | Disk 1 | 2→3 | [4,3] | [] | [2,1] |
| 4 | Disk 3 | 1→2 | [4] | [3] | [2,1] |
| 5 | Disk 1 | 3→1 | [4,1] | [3] | [2] |
| 6 | Disk 2 | 3→2 | [4,1] | [3,2] | [] |
| 7 | Disk 1 | 1→2 | [4] | [3,2,1] | [] |
| 8 | Disk 4 | 1→3 | [] | [3,2,1] | [4] |
| 9 | Disk 1 | 2→3 | [] | [3,2] | [4,1] |
| 10 | Disk 2 | 2→1 | [2] | [3] | [4,1] |
| 11 | Disk 1 | 3→1 | [2,1] | [3] | [4] |
| 12 | Disk 3 | 2→3 | [2,1] | [] | [4,3] |
| 13 | Disk 1 | 1→2 | [2] | [1] | [4,3] |
| 14 | Disk 2 | 1→3 | [] | [1] | [4,3,2] |
| 15 | Disk 1 | 2→3 | [] | [] | [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 ↓Hide 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)=1
- Closed Form: T(n)=2n−1 moves.
- Time Complexity: Θ(2n).
- Space Complexity: Θ(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 P in text T. State its best-case and worst-case time complexities.
Show solution ↓Hide solution ↑
Solution
Let text T have length n and pattern P have length m≤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) (e.g., T="AAAAAAAAAB", P="AAB").
- Best-Case Time Complexity: Θ(n) (when the first character of P immediately mismatches).
- Space Complexity: Θ(1) auxiliary space.
Exercise 4.2
(7 points) Board D stores characters in a 2-dimensional array. Pattern P could be read horizontally (left-to-right) or vertically (top-to-bottom). Write a brute-force algorithm to search for pattern P in board D, and state its time complexity.
Show solution ↓Hide solution ↑
Solution
Let board D have R rows and C columns, and pattern P have length m:
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×C board, each of the R⋅C cells performs at most 2m comparisons, giving Θ(R⋅C⋅m).
- For an n×n square board, the complexity is Θ(n2⋅m).
Section 5: Assignment Problem Using Exhaustive Search
Exercise 5
(7 points) Using exhaustive search to solve the assignment problem below. Find the minimum-cost assignment and state the time complexity.
| Person | Job 1 | Job 2 | Job 3 | Job 4 |
|---|
| Person A | 5 | 11 | 4 | 3 |
| Person B | 6 | 10 | 3 | 8 |
| Person C | 7 | 9 | 4 | 6 |
| Person D | 10 | 12 | 6 | 9 |
Show solution ↓Hide solution ↑
Solution
Each person must be assigned to exactly one job, and each job assigned to exactly one person.
Exhaustive search enumerates all 4!=24 permutations and keeps the cheapest.
Minimum-cost assignment:
J1→B(6),J2→C(9),J3→D(6),J4→A(3)Cost=6+9+6+3=24This is the unique optimum. Two runner-up permutations cost 25 and are the ones most often
stopped at when the enumeration tree is pruned by eye rather than completed:
- A→J4(3)+B→J3(3)+C→J2(9)+D→J1(10)=25
- A→J4(3)+B→J3(3)+C→J1(7)+D→J2(12)=25
Both fix A→J4 and B→J3 because those are each row’s cheapest cell, but the greedy
row-wise choice is not optimal here: paying 6 instead of 3 for B frees J3 for D, whose
alternatives are all far more expensive.
Time Complexity: Generating and evaluating all permutations takes Θ(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 ↓Hide 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 2n(n−1) pairs ⟹Θ(n2).
- Space Complexity: Θ(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 ↓Hide solution ↑
Solution
- Step 1 (Divide): Sort all points by x-coordinate. Divide the set into two equal subsets PL and PR using a vertical line x=m.
- Step 2 (Conquer): Recursively compute the minimum pairwise distance in the left half (dL) and right half (dR).
Set d=min(dL,dR).
- Step 3 (Combine): Check for points spanning across the dividing line:
- Construct a vertical strip of width 2d (m−d≤x≤m+d).
- Sort the strip points by y-coordinate.
- For each point in the strip, inspect only subsequent points whose y-difference is strictly less than d. Geometrically, at most 6 points can fit in this region without violating the minimum distance condition.
- Recurrence & Complexity:
T(n)=2T(n/2)+Θ(n)
By the Master Theorem, the time complexity is Θ(nlogn), improving upon the Θ(n2) 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+c0where c2=a1b1, c0=a0b0, and c1=(a1+a0)(b1+b0)−c2−c0.
Compute 2134×5687 using this divide-and-conquer technique.
Show solution ↓Hide solution ↑
Solution
Let m=2:
- A=2134⟹a1=21, a0=34
- B=5687⟹b1=56, b0=87
Step 1: Compute c2
c2=a1×b1=21×56=1176Step 2: Compute c0
c0=a0×b0=34×87=2958Step 3: Compute c1
(a1+a0)(b1+b0)(a1+a0)(b1+b0)c1=21+34=55=56+87=143=55×143=7865=7865−c2−c0=7865−1176−2958=3731Step 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
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 ↓Hide solution ↑
Solution
- Division into Subproblems:
The integers of n digits are divided into high and low halves of n/2 digits (a1,a0 and b1,b0).
- Number of Subproblems:
Traditional multiplication requires 4 subproblems (a1b1,a1b0,a0b1,a0b0). Karatsuba’s formula computes c1 using only one additional product (a1+a0)(b1+b0) and linear additions/subtractions, reducing the count to 3 recursive subproblems.
- Recurrence Relation:
T(n)=3T(n/2)+Θ(n)
- Time Complexity:
By the Master Theorem (a=3,b=2,d=1, since a>bd=21):
T(n)∈Θ(nlog23)≈Θ(n1.585)
This is asymptotically superior to the Θ(n2) pencil-and-paper algorithm.