Algorithms in Engineering - Exam of 26 June 2025
Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.
In questa pagina 3
Written exam of 26 June 2025, translated into English from the equivalent course taught in Italian ("Algoritmi per l'Ingegneria", Engineering, University of Padua). The sheet reproduced here is Part 2 only (problem solving): two problems worth 17 and 16 points, 33 points in total. Part 1 (the closed-answer questionnaire on the basics of the course) is not public and is not part of this document. The duration is not printed on the sheet.
Official examination format of the course (2026-27): a written test in two parts, (1) a closed-answer questionnaire on the basics of the course and (2) problems (development and analysis of an algorithm, proof of a property). The second part may be left uncorrected if the first is seriously insufficient; if the test is insufficient, the whole test is retaken. The lecturer may add an optional oral exam. The use of AI is forbidden.
The text of the problems is translated faithfully; the solutions are written here and checked against the official solution of the course: all results coincide, and a few misprints of the official solution are pointed out (they are collected at the end of each exercise). Every algorithm and formula was implemented in Python and run (operation counts included): see "Checks performed" in each exercise. Pseudocode follows the conventions of the notes (Computational Problems, Algorithms and Cost ModelA computational problem is a total, not necessarily single-valued relation between instances and solutions; an algorithm is a function from instances to solutions and solves the problem if its output is always related to its input. Correctness means agreement with the specification; complexity is the cost as a function of input size, by default in the worst case, with unit-cost instructions chosen meaningfully.Computational Problems, Algorithms and Cost Model →).
Exercise 1 (points 17)
Let be the principal -th root of unity of order in the complex field. For every even natural number , define the polynomial
Note that vanishes at the -th roots of unity, except for and . The polynomial has degree , but it is convenient to regard it with degree bound and write
where the coefficients are uniquely determined by .
In all parts of the problem, by the complexity of an algorithm we mean the number of arithmetic operations on complex operands.
1.(a) [4 points] Describe a simple algorithm that, given as input, returns and . Analyze the complexity of .
1.(b) [3 points] Does the proposed algorithm have polynomial complexity? Justify the answer.
1.(c) [5 points] Describe an efficient algorithm (possibly ) for the computation of the DFT of the vector and analyze its complexity . (Recall the relation between the DFT and the evaluation of a polynomial at a suitable set of points.)
1.(d) [5 points] Describe an efficient algorithm (possibly ) for the computation of the coefficients of , proving its correctness and analyzing its complexity .
Show the result
- (a) evaluates the defining product at and at , sharing the powers of : . Since is an even function, and one evaluation is enough: operations (and for a single evaluation of the plain product).
- (b) No. The input is the integer , of size bits, and : the cost is exponential in the input size.
- (c) , with in position and zeros elsewhere. Cost (using the plain product it would be , also ).
- (d) for even and for odd ; the cost is . Indeed , so for even and otherwise: .
Show the full solution
First, what the polynomial is. The numbers are the roots of (DFT and Roots of UnityThe DFT of order n evaluates a polynomial with degree bound n at the n n-th roots of unity, y_i = p(w^i) with w = e^{2 pi i/n}; it is the product by the Fourier matrix F_n, an invertible Vandermonde matrix. The roots form a multiplicative group and satisfy three lemmas: cancellation (w_{dn}^{dk} = w_n^k, w_n^{n/2} = -1), halving (the squares of the n roots are the n/2 roots of order n/2, each twice) and summation (the sum of the powers of w^k is n if k is a multiple of n, 0 otherwise). Linear convolution theorem: (c|0) = DFT^{-1}{2n}(DFT{2n}(a|0) times DFT_{2n}(b|0)).DFT and Roots of Unity →). is the monic polynomial that keeps of them and drops the two real ones, and (the corollary of the cancellation lemma; here is even but not necessarily a power of two). Example, : , with coefficient vector . The coefficient is because the degree is (this is the "" of the text), and because is monic.
Point (a): the simple algorithm . Evaluate the defining formula directly at and at . The cost model is the one of the text: each arithmetic operation between complex numbers costs (the constant itself and the constants are free). The set of exponents is , which has elements.
A0(n)
P[1] <- w_n { the constant e^(i 2 pi / n) }
for h <- 2 to n-1 with h != n/2 do
P[h] <- P[h-1] * w_n { one multiplication per power }
{ (for h = n/2 + 1 use w^(n/2) = -1 as P[h-1]) }
u <- 1 - P[1]; v <- -1 - P[1] { first factors at x = +1 and x = -1 }
for h <- 2 to n-1 with h != n/2 do
u <- u * (1 - P[h]) { 1 subtraction + 1 product }
v <- v * (-1 - P[h]) { 1 subtraction + 1 product }
return (u, v)Correctness is immediate: u and v are the products of the factors , , at and , i.e. the definition of .
Cost. The powers with , are values, one multiplication each (the power with is the constant). The two evaluations share them. Each evaluation has factors , so subtractions, and products to multiply the factors together:
A single evaluation costs . Without sharing the powers the two evaluations would cost ; sharing saves multiplications and gives .
Better constants. Pair the factor with the factor , for . Since ,
The right-hand side depends only on , so for every ( is an even polynomial). In particular : one evaluation is enough. The product has factors and by the cancellation lemma:
A0'(n)
m <- n/2
P[1] <- w_m { constant, w_m = w_n^2 }
for h <- 2 to m-1 do P[h] <- P[h-1] * w_m { m-2 multiplications }
u <- 1 - P[1]
for h <- 2 to m-1 do u <- u * (1 - P[h]) { m-2 subtractions + m-2 products }
return (u, u) { p(1) = p(-1) }At we have (no multiplication). The cost is , i.e.
This agrees with the official . Example (): , because (summation lemma) and : , cost .
Observation (also in the official solution). One has , but that formula cannot be used to compute : the coefficients are not given, they are what the later parts compute.
Typical errors: forgetting that the factor is missing (the product would contain and would not be ); counting the powers of twice (once for and once for ); writing because the problem "looks like" an FFT: no transform is needed here.
Point (b): is polynomial? "Polynomial complexity" means polynomial in the size of the input (Computational Problems, Algorithms and Cost ModelA computational problem is a total, not necessarily single-valued relation between instances and solutions; an algorithm is a function from instances to solutions and solves the problem if its output is always related to its input. Correctness means agreement with the specification; complexity is the cost as a function of input size, by default in the worst case, with unit-cost instructions chosen meaningfully.Computational Problems, Algorithms and Cost Model →: size = reasonable measure of the encoding; for an integer it is the number of bits). The input of the problem is the single integer , written in binary with bits. Then
A function that is at least is not bounded by any polynomial in (for every constants one has for large ). So is exponential in the input size. It is linear in the value of , which is not the same: this is the same phenomenon as trial division for primality (see the example on the size of an integer in the cost-model note). The improved version , with operations, is exponential in the size too: halving the constant does not change the class.
Remark. This concerns the algorithm, not the problem: with (shown in point (d)) one gets with a single division, so the problem is solvable with arithmetic operations.
Misprint in the official solution: the official text writes "". But , not , and is false (). The correct chain is ; the conclusion (exponential) is unchanged.
Point (c): the DFT of . By definition (DFT and Roots of UnityThe DFT of order n evaluates a polynomial with degree bound n at the n n-th roots of unity, y_i = p(w^i) with w = e^{2 pi i/n}; it is the product by the Fourier matrix F_n, an invertible Vandermonde matrix. The roots form a multiplicative group and satisfy three lemmas: cancellation (w_{dn}^{dk} = w_n^k, w_n^{n/2} = -1), halving (the squares of the n roots are the n/2 roots of order n/2, each twice) and summation (the sum of the powers of w^k is n if k is a multiple of n, 0 otherwise). Linear convolution theorem: (c|0) = DFT^{-1}{2n}(DFT{2n}(a|0) times DFT_{2n}(b|0)).DFT and Roots of Unity →) the DFT of the coefficient vector of a polynomial of degree bound is the vector of its values at the -th roots of unity:
- For , is one of the roots kept in the product, so (a factor of the product is zero).
- For : . For : (point (a)).
DFT_P(n)
(u, u) <- A0'(n) { u = p(1) = p(-1) }
for h <- 0 to n-1 do A[h] <- 0 { assignments, not arithmetic }
A[0] <- u; A[n/2] <- u
return ACost. All the arithmetic is in the call to : . Filling the entries costs assignments, which are not arithmetic operations (the output has components anyway, so no algorithm can be faster than linear in the size of the output). This is far below the of the general FFT (Fast Fourier TransformThe FFT computes the DFT_n (n a power of two) by divide and conquer: split the coefficients by index parity, p(x) = p0(x^2) + x p1(x^2), and by the halving lemma two DFTs of order n/2 suffice; y_i = y0_i + w^i y1_i and y_{i+n/2} = y0_i - w^i y1_i. The recurrence T(n) = 2T(n/2) + 2n with T(1) = 0 has exact solution 2 n log2 n. The inverse has matrix F^{-1}{ij} = w^{-ij}/n and is obtained with the FFT on negative powers (then dividing by n outside the recursion) or with a reversed DFT_n(y). LIN_CONV multiplies two polynomials with n coefficients in 12 n log2(2n) + 4n operations.Fast Fourier Transform →) because the vector is highly structured; the same idea appears for sparse inputs in Notable Transforms and Polynomial ExponentiationSome vector families have a known or cheaper DFT than the general FFT: the constant vector (a,...,a) has DFT (na,0,...,0), the vector (a,0,...,0) has DFT (a,...,a); an (n,k)-sparse vector has a DFT made of k copies of the DFT{n/k} of its components at multiples of k, and SPARSE_FFT costs 2 (n/k) log2(n/k) with recurrence T(n,k) = T(n/2,k/2). For the power p(x)^k of a polynomial with n coefficients: either repeated squaring with LIN_CONV, O(nk log(nk)), or evaluate p with the FFT on h = 2^ceil(log2((n-1)k+1)) points, raise each value to the k, and invert, Theta(nk log(nk)).Notable Transforms and Polynomial Exponentiation → (the official solution notes that is also -sparse, since for odd : this is an alternative route).
The official solution writes , the cost of one evaluation of the plain product (legitimate: a single evaluation suffices because ); with the product over the constant drops to . Both are .
Point (d): the coefficients. The coefficient vector is the inverse DFT of (Fast Fourier TransformThe FFT computes the DFT_n (n a power of two) by divide and conquer: split the coefficients by index parity, p(x) = p0(x^2) + x p1(x^2), and by the halving lemma two DFTs of order n/2 suffice; y_i = y0_i + w^i y1_i and y_{i+n/2} = y0_i - w^i y1_i. The recurrence T(n) = 2T(n/2) + 2n with T(1) = 0 has exact solution 2 n log2 n. The inverse has matrix F^{-1}_{ij} = w^{-ij}/n and is obtained with the FFT on negative powers (then dividing by n outside the recursion) or with a reversed DFT_n(y). LIN_CONV multiplies two polynomials with n coefficients in 12 n log2(2n) + 4n operations.Fast Fourier Transform →: ). Only and are nonzero, so only two terms survive:
(Here .) With :
The vanishing of the odd coefficients also follows directly from the fact that is an even polynomial (point (a)): forces .
COEFF(n)
(u, u) <- A0'(n) { u = p_n(1) }
c <- u / (n/2) { 1 division: c = (2/n) p_n(1) }
for i <- 0 to n-1 do
if i is even then a[i] <- c else a[i] <- 0
return aCorrectness. By the inverse DFT theorem the computed vector is the unique coefficient vector with DFT equal to the one found in point (c); the chain of equalities above shows that it is exactly COEFF's output (even index: ; odd index: ).
Cost. arithmetic operations (plus assignments). If the plain product is used, .
Closed form (not required, but it closes the exercise). The roots of unity are the roots of , a monic polynomial, so . Hence
(a geometric sum in with terms). So , and for even , otherwise. Examples: : and DFT ; : and DFT .
Typical errors: forgetting the division by of the inverse DFT; using instead of (here harmless, because is real, but wrong in general); concluding that all the coefficients with even index are instead of ; applying the full FFT, which is correct but costs and needs to be a power of two (here is only even).
Misprints in the official solution: in point (d) the official text calls the complexity instead of , and refers to "the expression for the 's from part 1.(d)" where it means part 1.(c). The results are unaffected.
Checks performed. (Python, instrumented counters for the arithmetic operations.) For every even from to (including not a power of two, e.g. ): the coefficients of (product of the factors for ) equal for even and otherwise; the values computed from the definition give the vector , i.e. the DFT of point (c); returns with exactly operations, with exactly , COEFF reproduces the coefficient vector with exactly ; the single plain evaluation costs . The identity was checked numerically for at a complex test point, and for many values of .
Exercise 2 (points 16)
Given a vector of positive integers, consider the following recurrence, defined for :
2.(a) [10 points] Give the pseudocode of the pair of procedures INIT_T and REC_T that, given the vector as input, perform the memoized computation of .
2.(b) [6 points] Determine the exact number of comparisons and sums between integers performed by the memoized algorithm.
Show the result
- (a)
INIT_Treturns if ; otherwise it fills the first row and the last column with the base values, sets the other entries (, ) to the sentinel (valid because every ) and returnsREC_T.REC_T, if , computesREC_TREC_TandREC_T, stores in , and returns . - (b) (one sum and one comparison for each of the cells with and ).
Show the full solution
What the recurrence asks. The cell depends on three other cells: above, to the right and above-right. The first row and the last column are base cases (they are given by ; the corner is consistent: both rules give ). The goal is the bottom-left corner. Example, , ; the table (row , column ) is
| 3 | 1 | 4 | 2 | |
| 12 | 9 | 8 | 4 | |
| 30 | 18 | 9 | 1 | |
| 60 | 30 | 12 | 3 |
For instance and . The last column is : , , .
Point (a): the memoized code (Dynamic Programming - Paradigm and Memoizationdynamic programming improves on divide and conquer by storing the solutions of repeated subinstances in a table; Fibonacci shows the gap (F_n - 1 additions recursively, n - 1 with a table), memoization is recursion plus a global table, and optimization problems follow a five-step scheme built on optimal substructure and cut-and-paste.Dynamic Programming - Paradigm and Memoization →, and the worked pattern in Memoization of Triangular Recurrencesfor the recurrence M(i,j) = M(i+1,j-1) M(i+1,j) M(i,j-1) on the triangle 1 <= i <= j <= n, standard memoized code performs exactly (n-1)(n-2) multiplications, but all entries on a diagonal are equal, which cuts the work to 2(n-2) multiplications; look for regularities before filling a table.Memoization of Triangular Recurrences →). Two design decisions have to be justified.
- The sentinel. The table must tell "already computed" from "still to compute". Since all components of are positive, every is positive (induction: base values are components of ; a sum of positive numbers and a maximum of positive numbers are positive). So is never a possible value and is a valid sentinel.
- Who fills what.
INIT_Thandles the base cases (first row and last column, written directly from ) and sets all the other cells to the sentinel, then makes the only call that starts the recursion.REC_Tcomputes the non-base cells.
INIT_T(x)
n <- x.length
if n = 1 then return x[1] { t(n,1) = t(1,1) = x_1: base case }
for i <- 1 to n do
T[1, i] <- x[i] { first row: t(1,j) = x_j }
T[n+1-i, n] <- x[i] { last column: t(k,n) = x_{n+1-k}, k = n+1-i }
for i <- 2 to n do
for j <- 1 to n-1 do T[i, j] <- 0 { cells still to be computed }
return REC_T(x, n, 1)
REC_T(x, i, j)
if T[i, j] = 0 then { only non-base cells can be 0 }
s <- REC_T(x, i-1, j) + REC_T(x, i, j+1) { 1 sum }
m <- REC_T(x, i-1, j+1)
if m >= s then T[i, j] <- m { 1 comparison }
else T[i, j] <- s
return T[i, j]Correctness. Consider the quantity , which is only for the cell . The three calls from go to cells with smaller by , and respectively, and they are legitimate cells of the table: because and because . Hence the recursion terminates, and by induction on REC_T returns and leaves :
- if the cell is a base cell, already holds the right value and is non-zero, so it is returned directly;
- if it is a non-base cell with , the three recursive calls return the right values by induction (smaller ), so the stored value is , which is by definition;
- if it is a non-base cell with , then it was already computed correctly earlier, by the same argument.
As in the official solution, one can observe that an entry of is read in the right-hand side of an assignment only after the corresponding call has completed, so it holds its final value. The case is solved directly by INIT_T (the table is not needed).
Typical errors: using as a sentinel without noticing that positivity is what makes it legal (with arbitrary integers the code would recompute cells, or return wrong values); swapping the indices of the last column ( instead of ); forgetting to initialize the non-base cells to the sentinel; calling REC_T instead of REC_T; writing the plain recursion without a table (see below, it takes exponential time).
Point (b): exact count. As in Memoization of Triangular Recurrencesfor the recurrence M(i,j) = M(i+1,j-1) M(i+1,j) M(i,j-1) on the triangle 1 <= i <= j <= n, standard memoized code performs exactly (n-1)(n-2) multiplications, but all entries on a diagonal are equal, which cuts the work to 2(n-2) multiplications; look for regularities before filling a table.Memoization of Triangular Recurrences →, count the internal nodes of the call tree, not a recurrence on the operations, because a recurrence describes the purely functional execution in which every node is expanded, whereas here a call on a filled cell is a table read (Divide and Conquer - Paradigm and Call TreeA divide-and-conquer algorithm comes from a substructure property (threshold n0, Divide and Conquer functions) with strictly smaller subinstances; the call tree describes the execution, and D&C has no memory (equal subinstances are recomputed). Complete example: MAX of an array, with correctness by induction, the recurrence, and the exact count n-1 via the theorem on full binary trees.Divide and Conquer - Paradigm and Call Tree →).
INIT_Tperforms only assignments: no sum and no comparison.- In the tree of
REC_T, a call that finds is a leaf with no work (base cell or already computed cell). A call that finds is an internal node that performs one sum and one comparison: work . - Which cells are internal nodes, and how many times? The non-base cells are exactly the pairs with and : that is cells. Each of them is reached: from one gets to with steps of type (reaching ) followed by steps of type ; all the intermediate cells have and , so they are non-base and are expanded on the way. Each is an internal node exactly once: after the first expansion and every later call is a read.
Check, : operations (9 sums and 9 comparisons); : . The algorithm is . Without the table the same recurrence takes exponential time: the call tree of the plain recursion has nodes for , whereas the memoized code does operations for .
Typical errors: counting only the sums, or only the comparisons (the text asks for both, per cell); counting all cells (the base cells do no work: instead of ); using the operation recurrence of the unmemoized tree; counting with or .
An extra observation (optional, from the official solution). The table is symmetric with respect to the antidiagonal: . Proof. Let . Then and : the same base cases as . For and , unfolding with and and rewriting each term as a value of gives : the same recurrence. Two functions with the same base cases and the same recurrence coincide, so . (In the example above and .) It is therefore enough to compute the cells with and to replace any other cell by its mirror image before reading or writing the table. Now only cells are non-base, and the count becomes instead of : the leading constant of halves ( against : against for ). This was left as a challenge in the official solution; it was implemented and the count checked.
Checks performed. (Python.) The memoized code, written exactly as the pseudocode above, was compared with the direct (unmemoized) evaluation of the recurrence on random vectors of positive integers for every from to : the values coincide on all of them, and the counted operations (sums plus comparisons) are exactly for every case. The example gives the table above, and operations. The antidiagonal symmetry was verified on random vectors for each from to , and the version with mirrored cells returns the same values with exactly operations for . The sizes of the unmemoized call tree quoted above come from counting the nodes of the plain recursion. No misprint was found in the official solution of this exercise.
Self-assessment grid
| Exercise | Points | What must be there for full marks | Typical errors |
|---|---|---|---|
| 1.(a) | 4 | Algorithm that evaluates the product at with the factor excluded; exact or count: (shared powers), or using | Including the missing factor; counting the powers of twice; using (the are unknown); claiming |
| 1.(b) | 3 | Size of the input is bits; hence exponential, not polynomial | Answering "linear, so polynomial" (linear in the value, not in the size); wrong inequality |
| 1.(c) | 5 | DFT values at ; zeros except positions and ; , ; cost | Running the general FFT; forgetting (two evaluations: still , but unjustified); putting the second nonzero entry at the wrong position |
| 1.(d) | 5 | Inverse DFT with only two terms, from , so (even ), (odd ); proof of correctness; cost | Missing the ; for even ; no proof (correctness must be argued from the inverse DFT theorem or from being even) |
| 2.(a) | 10 | INIT_T with base row, base column (index ), sentinel justified by positivity, call on ; REC_T with the three calls, one sum, one comparison, table assignment; termination and correctness argued |
Wrong indices in the last column; sentinel not justified; missing table or initialization; recursion without memoization |
| 2.(b) | 6 | Internal nodes the non-base cells, each once; work per node (sum and comparison); | (base cells counted); only sums or only comparisons; using the recurrence of the unmemoized tree |