What is the minimum number of digits needed to write the natural number $n=1000$ in base $2$?
$9$
$11$
$4$
$10$
Explanation. The minimum number of digits is $\lfloor\log_2 n\rfloor+1$: since $2^9=512\le 1000<1024=2^{10}$, we have $\lfloor\log_2 1000\rfloor=9$ and $10$ digits are needed.
What is the representation interval of the integers in sign-magnitude with $k=8$ bits?
$[-128,\,127]$
$[-127,\,127]$
$[-128,\,128]$
$[0,\,255]$
Explanation. The magnitude uses $k-1=7$ bits, so it is at most $2^{7}-1=127$: the interval is $[-(2^{k-1}-1),\,2^{k-1}-1]=[-127,127]$. $[-128,127]$ is the one of two's complement.
What is the representation interval of the integers in two's complement with $k=6$ bits?
$[-31,\,31]$
$[-31,\,32]$
$[-32,\,31]$
$[-64,\,63]$
Explanation. With $k$ bits the interval is $[-2^{k-1},\,2^{k-1}-1]=[-32,31]$: the $2^{5}$ sequences with most significant bit $1$ represent $-32,\dots,-1$, and zero has a unique representation.
Which statement about the sign-magnitude representation with $k$ bits is correct?
Zero has two representations, so the $2^k$ sequences represent only $2^k-1$ different integers.
Zero has a unique representation, as in two's complement.
Two integers are added as natural numbers, discarding the final carry.
The most significant bit is $1$ for the non-negative integers.
Explanation. $(00\dots0)_2=+0$ and $(10\dots0)_2=-0$: two sequences for the same integer. Two's complement solves the problem (a unique zero) and allows adding as for natural numbers.
In IEEE 754 single precision ($1$ sign bit $s$, $8$ bits of biased exponent $E$, $23$ fraction bits $f$, normalized number) we have $s=0$, $E=(10000010)_2$ and $f=0100\dots0$. Which number is represented?
$5$
$2$
$10$
$20$
Explanation. $E=130$, hence $e=E-127=3$; the significand is $(1.01)_2=1.25$ and the number is $1.25\cdot 2^3=10$. Forgetting the implicit $1$ gives $0.25\cdot 8=2$; using $128$ as the bias gives $5$.
In IEEE 754 single precision (significand $(1.f)_2$ with $23$ fraction bits $f$, exponent between $-126$ and $127$), what is the distance between $1$ and the next representable number (machine epsilon)?
$2^{-23}$
$2^{-24}$
$2^{-126}$
$2^{-127}$
Explanation. $1=(1.00\dots0)_2\cdot 2^0$; the next number sets to $1$ the last of the $23$ fraction bits, whose weight is $2^{-23}$. $2^{-126}$ is instead the smallest positive normalized number.
The two's complement representations with $k$ bits of $n_1$ and $n_2$ are added as natural numbers, keeping the $k$ least significant bits; there is an overflow when the result does not represent $n_1+n_2$. Which statement is correct?
There is an overflow if and only if the sum produces a carry out of the most significant bit, which is discarded.
There is an overflow if and only if $n_1$ and $n_2$ have the same sign and the sign bit of the result is the opposite one.
There is an overflow if and only if $n_1$ and $n_2$ have different signs and the result has the sign of the larger in absolute value.
There is never an overflow: the result always represents $n_1+n_2$, because the final carry is discarded.
Explanation. Overflow means $n_1+n_2\notin[-2^{k-1},2^{k-1}-1]$ (Observation 1.13). A discarded carry does not mean overflow: for instance $3+(-1)$ with $4$ bits discards a carry and correctly gives $2$. With different signs the sum lies between $n_1$ and $n_2$ and there is never an overflow.
Corollary 1.12 gives the minimum number of bits of an integer $n$ in two's complement ($\lfloor\log_2 n\rfloor+2$ if $n>0$, $\lceil\log_2|n|\rceil+1$ if $n<0$). What is needed to prove it?
The binary digits of $|n|$ are $\lfloor\log_2|n|\rfloor+1$, and this number of bits is already enough for every integer $n\ne 0$.
The result on addition: $n$ fits in $k$ bits if and only if $n+n$ gives no overflow with $k$ bits.
The interval $[-(2^{k-1}-1),\,2^{k-1}-1]$ of sign-magnitude, which has the same number of bits for $n$ and $-n$.
The minimum is the smallest $k$ with $-2^{k-1}\le n\le 2^{k-1}-1$; then the monotonicity of $\log_2$ and the definitions of $\lfloor\cdot\rfloor$ and $\lceil\cdot\rceil$.
Explanation. For $n>0$ the condition becomes $n<2^{k-1}$, i.e., $\log_2 n<k-1$; for $n<0$ it becomes $|n|\le 2^{k-1}$, i.e., $\log_2|n|\le k-1$: hence floor $+2$ and ceiling $+1$. The digits of $|n|$ alone forget the sign bit.
Observation 1.9 states that the two's complement representation of $n<0$ is obtained by inverting the bits of $|n|$ and adding $1$. What is the proof based on?
Adding the representations of $n$ and of $|n|$ gives zero, discarding the carry out of the most significant bit.
On the uniqueness of quotient and remainder in the successive divisions by $2$ that produce the digits of $|n|$.
Inverting the bits of $|n|$ gives $(2^k-1)-|n|$ (geometric sum); adding $1$ gives $2^k+n$, i.e., the definition.
Inverting the sign bit of the sign-magnitude representation of $n$ gives $-n$, and the $+1$ fixes the double zero.
Explanation. The proof is a direct computation: the inverted bits give $2^k-1-|n|$, plus $1$ gives $2^k-|n|=2^k+n$. One also checks that the result fits in $k$ bits, since $1\le|n|\le 2^{k-1}$.
In positional notation with a fractional part, the digit $d_i$ in position $i$ (positive left of the point, negative right of it) weighs $d_i\,2^i$. Which number does $(110.101)_2$ represent?
$6.101$
$6.625$
$6.3125$
$3.625$
Explanation. $(110.101)_2=2^2+2^1+2^{-1}+2^{-3}=4+2+0.5+0.125=6.625$. Reading the digits after the point as decimal digits gives $6.101$; starting the weights from $2^{-2}$ instead of $2^{-1}$ gives $6.3125$.
In normalized binary scientific notation $x=(-1)^s\cdot(1.f_1f_2\dots)_2\cdot 2^e$, the sign is $s\in\{0,1\}$, the fraction $f=f_1f_2\dots$ consists of the bits after the point of the significand, and $e$ is the exponent. What are $s$, $f$ and $e$ for $x=-12.5$?
$s=1$, $f=11001$, $e=3$
$s=1$, $f=1001$, $e=4$
$s=0$, $f=1001$, $e=3$
$s=1$, $f=1001$, $e=3$
Explanation. $12.5=(1100.1)_2=(1.1001)_2\cdot 2^3$: the point moves $3$ positions, so $e=3$, and the fraction is $1001$ (the $1$ before the point is not part of $f$). The number is negative, so $s=1$.
In a positional numeral system every natural number is a sequence of digits. What distinguishes it from a system like the Roman one?
It uses only the digits $0$ and $1$
Every digit always has the same value, wherever it is
The contribution of a digit depends on its position in the sequence
It cannot represent zero
Explanation. In positional notation the same digit weighs different $b^i$ according to its position $i$: in $(707)_{10}$ the two $7$s are worth $700$ and $7$. Binary is just the case with base $2$.
The base $b$ of a positional numeral system is the number of distinct digits it uses. Which statement is correct?
It must be $b \ge 2$
It can be $b=1$, the unary system
It must be a power of $2$
It must be $b \le 16$
Explanation. With a single digit the position carries no information and only the length counts: this is why the unary system is not positional. Bases like $3$, $10$ or $60$ are allowed.
In sign-magnitude representation with $k=4$ bits the most significant bit is the sign ($0$ for $n \ge 0$, $1$ for $n<0$) and the other $3$ bits are the magnitude $|n|$ in binary. How is $-5$ represented?
$1011$
$0101$
$1101$
$1010$
Explanation. Sign $1$, magnitude $5=(101)_2$: $1101$. $1011$ is $-5$ in two's complement; $0101$ is $+5$.
In two's complement with $k$ bits the integers from $-2^{k-1}$ to $2^{k-1}-1$ are represented. What is the minimum number of bits to represent $n=-9$?
$5$
$4$
$6$
$3$
Explanation. With $k=4$ the interval is $[-8,7]$, which does not contain $-9$; with $k=5$ it is $[-16,15]$. So $k=5$; $4$ bits suffice for the magnitude $9$ in binary but not for the signed number.
In two's complement representation with $k=8$ bits, which bit string represents the integer $-1$?
$10000001$
$11111111$
$11111110$
$10000000$
Explanation. In two's complement $n<0$ is written as the natural number $2^k+n=256-1=255=(11111111)_2$. $10000001$ is $-1$ in sign-magnitude, $11111110$ is just the bitwise complement of $1$ (without adding $1$), $10000000$ is $-128$.
In two's complement with $k$ bits one represents the integers from $-2^{k-1}$ to $2^{k-1}-1$. Why is the interval not symmetric, while in sign-magnitude it is?
The sign bit is $1$ for positives, which takes one string from the negatives
It uses $k+1$ bits, and the extra bit serves only the negatives
The all-ones string represents no integer, like $-0$
Zero has a single representation, so one more string is left for the negatives
Explanation. All $2^k$ strings are used: $2^{k-1}$ with first bit $0$ (from $0$ to $2^{k-1}-1$) and $2^{k-1}$ with first bit $1$ (from $-2^{k-1}$ to $-1$). In sign-magnitude zero has two representations ($+0$ and $-0$).
In two's complement with $k=4$ bits one adds as naturals $0110$ (that is $6$) and $0011$ (that is $3$), keeping the $4$ least significant bits. Which string is obtained and what does it represent?
$1001$, which represents $-7$: overflow occurs
$1001$, which represents $9$: no overflow
$1001$, which represents $-1$: overflow occurs
$0001$, which represents $1$: the carry is dropped
Explanation. $6+3=9=(1001)_2$. In two's complement with $4$ bits $1001$ is $9-16=-7$: the sum of two positives gives a negative, because $9>2^{3}-1=7$ is outside the interval $[-8,7]$. $-1$ is the sign-magnitude reading.
In the IEEE 754 single-precision standard ($32$ bits: sign, biased exponent $E$, fractional part $f$), how many bits does the exponent have and which bias is subtracted from $E$ to get the exponent $e$?
$8$ bits, and $e=E-128$
$11$ bits, and $e=E-1023$
$8$ bits, and $e=E-127$
$7$ bits, and $e=E-63$
Explanation. Single precision: $1$ sign bit, $8$ exponent bits, $23$ fraction bits; the bias is $2^{7}-1=127$. $11$ bits and $1023$ are the double-precision values.
In IEEE 754 single precision a number is $(-1)^s\cdot(1.f)_2\cdot 2^e$ with $23$ bits of fractional part $f$. Why is the decimal number $0.1$ not represented exactly?
In base $2$ it has infinitely many digits after the point, and $f$ holds only $23$
It is smaller than the smallest representable normalised number
The exponent $e$ cannot be negative, so numbers below $1$ are lost
More than $8$ bits are needed for the sign of a number below $1$
Explanation. $0.1=(0.000110011\ldots)_2$ is periodic in base $2$: it must be truncated (rounded) to $23$ fraction bits. The smallest normalised number is about $1.2\cdot 10^{-38}$, far below $0.1$, and the exponent can be negative.
In the pseudo-code of the notes, which statement about $:=$ and $\leftarrow$ is correct?
A variable is declared with its initial value using $:=$ and later modified with $\leftarrow$.
A variable is declared with $\leftarrow$ and modified with $:=$.
$:=$ and $\leftarrow$ are synonyms and can be used interchangeably, also for variables not yet declared.
$\leftarrow$ compares two values and returns true or false.
Explanation. The declaration operator is $:=$ (name and initial value); the assignment $\leftarrow$ evaluates the expression on the right and its value replaces the old value of a previously declared variable.
What is the value of $\lfloor 17/5\rfloor+(17\bmod 5)$?
$6$
$4$
$5$
$3$
Explanation. $17=3\cdot 5+2$: the floor of the quotient is $3$ and the remainder is $2$, $5$ in total. With the ceiling ($\lceil 17/5\rceil=4$) one would get $6$.
How many iterations does the loop «for $i:=2$ to $2n$ step $2$» execute (with $n\ge 1$)?
$n$
$2n$
$n+1$
$2n-1$
Explanation. The variable $i$ takes the values $2,4,\dots,2n$, i.e., $n$ values: the step $2$ halves the number of iterations with respect to $i:=1$ to $2n$.
What is the value of $sum$ at the end? <pre>sum := 0
<b>for</b> i := 1 <b>to</b> 10 <b>do</b>
<b>if</b> i mod 3 = 0 <b>then</b>
<b>continue</b>
<b>end</b>
sum ← sum + i
<b>end</b></pre>
$55$
$18$
$12$
$37$
Explanation. continue skips the rest of the body for $i=3,6,9$: we add $1+2+\dots+10=55$ minus $3+6+9=18$, i.e., $37$.
What is the value of $i$ at the end? <pre>sum := 0
i := 1
<b>while</b> i ≤ 10 <b>do</b>
sum ← sum + i
<b>if</b> sum > 12 <b>then</b>
<b>break</b>
<b>end</b>
i ← i + 1
<b>end</b></pre>
$6$
$5$
$4$
$11$
Explanation. The partial sums are $1,3,6,10,15$: with $i=5$ we have $sum=15>12$ and break leaves the loop before the increment, hence $i=5$.
Which of the following is the definition of algorithm?
A sequence of unambiguous instructions that may not terminate, provided that every instruction can be executed.
A finite sequence of unambiguous instructions that, starting from some data given as input, produces a result given as output in a finite number of steps.
A program written in a programming language such as C++, Python or Java.
A high-level description that mixes natural language and programming language-like structures.
Explanation. Finiteness, unambiguity and termination in a finite number of steps are part of the definition. The description mixing natural language and programming language-like structures is the definition of pseudo-code, which is a way to describe an algorithm.
ReverseArray$(a,n)$ swaps $a[i]$ and $a[n-i+1]$ for $i:=1$ to $\lfloor n/2\rfloor$. How many swaps does it perform with $n=7$?
$3$
$4$
$7$
$6$
Explanation. $\lfloor 7/2\rfloor=3$: it swaps $a[1]\leftrightarrow a[7]$, $a[2]\leftrightarrow a[6]$, $a[3]\leftrightarrow a[5]$; the middle element $a[4]$ stays in place. Going up to $n$ would restore the original array.
A high-level description of an algorithm that mixes natural language and structures similar to those of programming languages.
A language with a rigid, fixed syntax, which a compiler translates into machine code like a C++ program.
A sequence of instructions that may also not terminate, provided each single instruction can be executed by the computer.
The line-by-line translation of a Python program, with the keywords translated into English or Italian.
Explanation. Pseudo-code is meant to communicate the logic of an algorithm to humans, not to be executed: that is why it mixes natural language and constructs such as if, while, for, without the syntax of a specific language.
In pseudo-code $:=$ declares a variable with its initial value and $\leftarrow$ assigns it a new value. What are $x$ and $y$ at the end? <pre>x := 3
y := 8
x ← y
y ← x</pre>
$x=8$, $y=3$
$x=3$, $y=3$
$x=8$, $y=8$
$x=3$, $y=8$
Explanation. $x\leftarrow y$ overwrites the old value $3$ of $x$ with $8$; then $y\leftarrow x$ copies into $y$ the current value of $x$, i.e., $8$. To exchange the values a temporary variable is needed: $tmp:=x$, $x\leftarrow y$, $y\leftarrow tmp$.
$\lfloor x\rfloor$ is the largest integer $\le x$, $\lceil x\rceil$ the smallest integer $\ge x$, $|x|$ the absolute value. What is $\lceil 7/2\rceil\cdot\lfloor 7/2\rfloor+|-3|+\max(-3,2)$?
$17$
$14$
$12$
$21$
Explanation. $\lceil 3.5\rceil=4$, $\lfloor 3.5\rfloor=3$, $|-3|=3$, $\max(-3,2)=2$: $4\cdot 3+3+2=17$. Using $3$ for both roundings gives $14$, and taking $-3$ as the maximum gives $12$.
In pseudo-code arrays are indexed from $1$: $a:=$ new array$[1..5]$ has the components $a[1],\dots,a[5]$. What does $a$ contain at the end? <pre>a := new array[1..5]
<b>for</b> i := 1 <b>to</b> 5 <b>do</b>
a[i] ← 2 · i
<b>end</b>
a[3] ← a[2] + a[4]</pre>
$[2, 4, 6, 16, 10]$
$[2, 12, 6, 8, 10]$
$[2, 4, 12, 8, 10]$
$[2, 4, 10, 8, 10]$
Explanation. After the loop $a=[2,4,6,8,10]$; then $a[3]\leftarrow a[2]+a[4]=4+8=12$. Counting the indices from $0$ leads to adding $6+10$ and writing into the fourth component, i.e., $[2,4,6,16,10]$.
In pseudo-code $b[i][j]$ is the component in row $i$ and column $j$ of a two-dimensional array, with indices from $1$. What is $b[2][3]$ at the end? <pre>b := new array[1..3][1..4]
<b>for</b> i := 1 <b>to</b> 3 <b>do</b>
<b>for</b> j := 1 <b>to</b> 4 <b>do</b>
b[i][j] ← 4 · (i − 1) + j
<b>end</b>
<b>end</b></pre>
$10$
$11$
$6$
$7$
Explanation. $b[2][3]=4\cdot(2-1)+3=7$: the value numbers the components in the order in which they are visited, row by row. Swapping row and column gives $4\cdot 2+2=10$; forgetting the $-1$ gives $11$.
The function IsSorted$(a,n)$ executes, for $i:=1$ to $n-1$, «<b>if</b> $a[i]>a[i+1]$ <b>then return</b> false», and after the loop «<b>return</b> true». On $a=[1,3,3,7,5,9,2]$, how many comparisons $a[i]>a[i+1]$ does it perform and what does it return?
$6$ comparisons, returns false
$4$ comparisons, returns false
$4$ comparisons, returns true
$2$ comparisons, returns false
Explanation. The comparisons for $i=1,2,3$ ($1>3$, $3>3$, $3>7$) are false; for $i=4$ we have $7>5$ and the return statement terminates the function at once. The equal pair $3,3$ does not violate the non-decreasing order.
In pseudo-code a set contains distinct elements: add $x$ to $s$ is ignored if $x$ is already present, remove $x$ from $s$ if $x$ is absent, and foreach visits the elements in insertion order. After $s:=$ new set, add $5$, add $2$, add $8$, add $2$, remove $7$, add $1$ (all on $s$), what does «<b>foreach</b> $x$ <b>in</b> $s$ <b>do</b> print$(x)$» print?
$1, 2, 5, 8$
$5, 2, 8, 2, 1$
$5, 2, 8, 1$
Nothing: remove $7$ gives an error, because $7$ does not belong to $s$
Explanation. The second add $2$ and remove $7$ leave $s=\{5,2,8\}$ unchanged; then $1$ is added. By convention foreach follows the insertion order: $5,2,8,1$. Increasing order is obtained only with «sorted by».
Another text writes $b_{ij}$ for the component in row $i$ and column $j$ of a matrix and uses $=$ both to declare and to assign. How is the same written in the style conventions of the pseudo-code of the notes?
$b[i][j]$; $:=$ for the declaration and $\leftarrow$ for the assignment
$b[i,j]$; $\leftarrow$ both for the declaration and for the assignment
$b_{ij}$; $:=$ both for the declaration and for the assignment
$b[j][i]$; $\leftarrow$ for the declaration and $:=$ for the assignment
Explanation. The notes use $a[i]$ and $b[i][j]$ (row, then column), declare with $:=$ and assign with $\leftarrow$. The other choices are legitimate in other texts: what matters is consistency.
An author of pseudo-code writes $a_i$ for the component of index $i$ of an array and puts comments after #. What do the style conventions of the notes say about it?
They are errors: pseudo-code has a fixed syntax, so one must always write $a[i]$ and // for comments.
$a_i$ is legitimate, but comments are forbidden: pseudo-code must explain itself, without notes.
They are legitimate choices if used consistently; the notes write $a[i]$ and comments after //.
They are legitimate only if $=$ is also used to declare, because the conventions must all come from the same text.
Explanation. The notes list the common variants ($:=$ or $=$, $\leftarrow$ or $=$, $a[i]$ or $a_i$, comments with //, # or (* *)) and conclude that what matters is being consistent and clear.
A description fixing the type and the bit size of every variable
A high-level description of an algorithm, meant for people
Explanation. Pseudo-code conveys the idea of the algorithm without the details of a real language; it is not run on a computer, but translated afterwards into C++, Python or Java.
An algorithm is a finite sequence of unambiguous instructions that produces the output in a finite number of steps. Which of the following procedures is NOT an algorithm?
Finding the maximum of an array by scanning it once
Converting $n$ to base $2$ by repeated division by $2$
Repeating «$x\leftarrow x+1$» with no stopping condition
Trying the divisors $d=2,\dots,\lfloor n/2\rfloor$ of $n$
Explanation. The first procedure never terminates, so it produces no result in a finite number of steps. The other three terminate on every input.
In the pseudocode of the notes a variable is declared with $:=$ (name and initial value) and modified with $\leftarrow$. Which fragment follows these rules?
$sum \leftarrow sum + 5$, without declaring $sum$ first
$sum := 0$, then $sum := sum + 5$
$0 := sum$, then $sum \leftarrow 5$
$sum := 0$, then $sum \leftarrow sum + 5$
Explanation. A variable is declared once, before use, with its initial value; every later change is an assignment with $\leftarrow$. The name, not the value, stands to the left of $:=$.
To find the maximum of $a[1..n]$ one declares $max := -\infty$ and then, for $i:=1$ to $n$, runs $max\leftarrow a[i]$ if $a[i]>max$. Why the initial value $-\infty$?
Because $0$ is not an allowed value in a declaration
So the first comparison always updates $max$, whatever $a[1]$ is
Because every variable not yet assigned is $-\infty$
Because then the loop can safely start at $i:=2$
Explanation. Every $a[1]$ is greater than $-\infty$, so after the first iteration $max=a[1]$. With $max:=0$ the result would be wrong on an all-negative array; starting at $i:=2$ requires $max:=a[1]$ instead.
In pseudocode ($:=$ declares, $\leftarrow$ assigns: the right-hand side is evaluated first) one runs <pre>a := 4
b := a + 1
a ← 2 · b
b ← a − b</pre> What are $a$ and $b$ at the end?
$a=10$, $b=-5$
$a=8$, $b=4$
$a=10$, $b=5$
$a=10$, $b=6$
Explanation. $b=5$, then $a=2\cdot 5=10$, then $b=10-5=5$. Assignment uses the current values: after the third line $a$ is already $10$.
$\lceil x\rceil$ is the smallest integer $\ge x$ and $\lfloor x\rfloor$ the largest integer $\le x$. What is $\lceil 17/4\rceil-\lfloor -7/2\rfloor$?
$9$
$8$
$7$
$1$
Explanation. $\lceil 4.25\rceil=5$ and $\lfloor -3.5\rfloor=-4$ (the largest integer less than or equal to $-3.5$), so $5-(-4)=9$. Rounding $-3.5$ towards zero ($-3$) gives $8$.
In pseudocode $a \bmod b$ is the remainder of the integer division of $a$ by $b$. Which expression is true if and only if the integer $i$ is even and a multiple of $3$?
$(i \bmod 2 = 0)$ or $(i \bmod 3 = 0)$
$(i / 2 = 0)$ and $(i / 3 = 0)$
$(i \bmod 2 = 0)$ and $(i \bmod 3 = 0)$
$(i \bmod 2 = 1)$ and $(i \bmod 3 = 0)$
Explanation. «Even» is $i\bmod 2=0$, «multiple of $3$» is $i\bmod 3=0$, and both must hold: and. With or one of them suffices; $i/2$ is the division, not the remainder.
Two pseudocode fragments are compared, with a condition $c$ and two blocks $S_1$, $S_2$. A: «if $c$ then $S_1$ end» followed by «if not $c$ then $S_2$ end». B: «if $c$ then $S_1$ else $S_2$ end». When can they behave differently?
Never: the two fragments are always equivalent
Whenever $c$ is false at the start
Only when $S_2$ contains a while loop
When $S_1$ modifies the variables $c$ depends on
Explanation. In B the condition is evaluated once. In A it is re-evaluated after $S_1$: if $S_1$ makes $c$ false, A also runs $S_2$. If $c$ is false at the start, both run only $S_2$.
The loop «for $i := s$ to $e$ do … end» is equivalent to «$i := s$; while $i \le e$ do … $i \leftarrow i+1$ end». With $s=5$ and $e=3$, how many times does the body run and how many times is the condition $i\le e$ evaluated?
The body $0$ times, the condition $0$ times
The body $0$ times, the condition $1$ time
The body $3$ times (with $i=5,4,3$)
The body $1$ time, the condition $2$ times
Explanation. The condition $5\le 3$ is false at the first check, so the body never runs; the for loop does not count down without a negative step.
One declares $b := $ new array$[1..3][1..4]$ (rows $1$ to $3$, columns $1$ to $4$) and sets $b[i][j]\leftarrow i\cdot j$ for every $i$ and $j$. What is the sum of row $2$, that is $b[2][1]+\dots+b[2][4]$?
$12$
$30$
$10$
$20$
Explanation. Row $2$ is $2,4,6,8$, with sum $20$. $12$ is the sum of column $2$ ($2+4+6$), $10$ the sum of the column indices alone.
One declares $t := $ new array$[1..2][1..3][1..4]$ and initialises it to $0$ with three nested for loops, one per dimension. How many components does $t$ have, and how many times does the assignment $t[i][j][k]\leftarrow 0$ run?
$9$ components, $24$ assignments
$24$ components, $24$ assignments
$24$ components, $9$ assignments
$9$ components, $9$ assignments
Explanation. There are $2\cdot 3\cdot 4=24$ components, and the nested loops visit every triple $(i,j,k)$ once. $9=2+3+4$ adds the dimensions instead of multiplying them.
In the pseudocode of the notes a multidimensional array is declared with $t := $ new array$[1..p][1..q][1..r]$. Which statement is correct?
The declaration assigns no values: every component must be initialised
The declaration automatically sets every component to $0$
Indices start at $0$, so $t[p][q][r]$ does not exist
At most three dimensions can be declared, like $p$, $q$, $r$
Explanation. new array creates the variables but gives them no value: nested for loops initialise them all. In the notes indices start at $1$, and there may be any number $k$ of dimensions.
CountPositive$(a,n)$ sets $count:=0$ and, for $i:=1$ to $n$, runs $count\leftarrow count+1$ if $a[i]>0$; then it returns $count$. What does it return on $a=[0,-1,3,0,5]$, $n=5$?
$4$
$3$
$2$
$5$
Explanation. Only $3$ and $5$ are greater than $0$. $4$ also counts the zeros (that is, it uses $a[i]\ge 0$).
In a pseudocode function, the return statement appears inside a for loop (as in IsSorted, which returns false at the first $a[i]>a[i+1]$). What happens when it is executed?
Only the loop ends, and execution continues after its end
Execution moves to the next iteration, as with continue
The value is stored and returned at the end of the loop
The whole function ends at once, returning the value
Explanation. return ends the whole function. This is what lets IsSorted stop after a single comparison on $[3,1,4,2]$.
A function declares $s := $ new set, runs add $a[i]$ to $s$ for $i:=1$ to $n$ (add is ignored if the element is already present) and returns size$(s)$. What does it return with $a=[4,7,4,4,2,7]$, $n=6$?
$6$
$4$
$2$
$3$
Explanation. The final set is $\{4,7,2\}$: the function counts the distinct values. $6$ also counts the duplicates.
A pseudocode fragment uses the variables $x_1$, $x_2$, $x_3$ for a sum, a counter and a maximum, and does not indent loop bodies. Which good style practices of the notes does it break?
None: pseudocode has no style rules
Only the bold type for the reserved words
Descriptive variable names and consistent indentation
Only line numbering, which is mandatory
Explanation. The notes ask for clear names ($sum$, $count$, $max$) and indentation that shows nested blocks; line numbers are useful but not mandatory.
InsertionSort, for $i=2,\dots,n$, inserts $\mathit{key}=a[i]$ into the sorted prefix $a[1..i-1]$: while $j\ge 1$ and $a[j]>\mathit{key}$ it shifts $a[j]$ into $a[j+1]$. How many comparisons $a[j]>\mathit{key}$ and how many shifts does it perform on an array of $n$ elements already sorted in non-decreasing order?
$\frac{n(n-1)}{2}$ comparisons and no shift
$n-1$ comparisons and no shift
$n-1$ comparisons and $n-1$ shifts
No comparison and no shift
Explanation. In each iteration $i=2,\dots,n$ the first comparison $a[i-1]>\mathit{key}$ is false and stops the inner loop: one comparison per iteration, no shift. This is the best case of Observation 3.5.
SelectionSort, for $i=1,\dots,n-1$, swaps $a[i]$ with the minimum of $a[i..n]$ (if different); ExchangeSort, for every pair $i<j$, swaps $a[i]$ and $a[j]$ if $a[i]>a[j]$. With $n=6$, what is the maximum number of swaps of each of them?
$15$ for both
$5$ for both
$15$ for SelectionSort, $5$ for ExchangeSort
$5$ for SelectionSort, $15$ for ExchangeSort
Explanation. SelectionSort performs at most one swap per iteration of the outer loop, hence $n-1=5$; ExchangeSort can swap at every comparison, up to $\frac{n(n-1)}{2}=15$ (decreasing array with distinct keys).
InsertionSort, for $i=2,\dots,n$, sets $\mathit{key}=a[i]$, $j=i-1$ and, while $j\ge 1$ and $a[j]>\mathit{key}$, shifts $a[j]$ into $a[j+1]$ and decrements $j$ (with $j=0$ it exits with no comparison). How many comparisons $a[j]>\mathit{key}$ and how many shifts does it perform on $[6,5,4,3,2,1]$?
$15$ comparisons and $5$ shifts
$15$ comparisons and $15$ shifts
$5$ comparisons and $15$ shifts
$21$ comparisons and $15$ shifts
Explanation. With distinct keys in decreasing order each $\mathit{key}$ moves to the first position: iteration $i$ makes $i-1$ shifts and $i-1$ comparisons (it exits with $j=0$ without a further comparison). In total $1+2+3+4+5=15$ and $15$.
SelectionSort, for $i=1,\dots,n-1$, looks for the minimum of $a[i..n]$ comparing $a[j]<a[\mathit{minIdx}]$ for $j=i+1,\dots,n$, then swaps it with $a[i]$. How many key comparisons does it perform on an array of $n=10$ elements?
From $9$ to $45$, depending on the input
Exactly $9$
Exactly $90$
Exactly $45$, on every input
Explanation. For each $i=1,\dots,n-1$ the inner loop compares $a[j]$ with $a[\mathit{minIdx}]$ for $j=i+1,\dots,n$: $\sum_{i=1}^{9}(10-i)=45$ comparisons, independently of the input.
A sort is in-place if it uses constant extra memory, stable if it preserves the relative order of records with equal keys. Which statement about Insertion Sort, Exchange Sort and Selection Sort is correct?
Insertion Sort is in-place and stable; Exchange Sort and Selection Sort are in-place but not stable.
All three are in-place and stable.
Insertion Sort and Selection Sort are stable, Exchange Sort is not.
Insertion Sort is stable but not in-place, because it shifts the elements.
Explanation. Observations 3.6, 3.8 and 3.10: all of them use a constant number of variables besides the array; only Insertion Sort never moves a key past an equal key.
Insertion Sort inserts $\mathit{key}=a[i]$ into the prefix $a[1..i-1]$ shifting to the right the keys $a[j]>\mathit{key}$. Which property is the proof that it is stable (preserves the relative order of equal keys) based on?
On the fact that the outer loop starts from $i=2$: the prefix $a[1..1]$ is already sorted and no key jumps over it.
On correctness: an array sorted in non-decreasing order always preserves the relative order of equal keys.
On the strict comparison $a[j]>\mathit{key}$: $\mathit{key}$ jumps only over strictly greater keys, never over an equal key that precedes it.
On the number of shifts, at most $\frac{n(n-1)}{2}$, one for each pair of keys in reverse order.
Explanation. With $a[j]\ge\mathit{key}$ as condition the algorithm would still be correct but not stable. Correctness alone is not enough: Selection Sort also sorts correctly without being stable.
Selection Sort, for $i=1,\dots,n-1$, swaps $a[i]$ with the first minimum of $a[i..n]$. How do we prove that it is not stable (i.e., that it does not always preserve the relative order of records with equal keys)?
It is enough to exhibit one input on which the relative order of two equal keys changes, e.g. $[(2,A),(2,B),(1,C)]$, which becomes $[(1,C),(2,B),(2,A)]$.
We show that it performs $\frac{n(n-1)}{2}$ comparisons on every input, more than a stable sort needs.
We show that it is not in-place, since the variable $\mathit{minIdx}$ stores a position of the array.
We prove by induction that after iteration $i$ the sub-array $a[1..i]$ contains the $i$ smallest keys sorted.
Explanation. To deny a universal property («on every input the order of equal keys is preserved») one counterexample is enough: the swap of $a[1]$ and $a[3]$ moves $(2,A)$ past $(2,B)$.
When it uses no variable at all besides the array to be sorted.
When it sorts the array without moving the elements already in place.
When the amount of extra memory it requires is constant, i.e., it does not grow with $n$.
When it preserves the relative order of records with equal keys.
Explanation. This is Definition 3.3: a few auxiliary variables ($i$, $j$, $\mathit{key}$, $\mathit{tmp}$) are allowed, as long as their number does not depend on $n$. Preserving the order of equal keys is stability.
ExchangeSort sorts $a[1..n]$: for $i=1,\dots,n-1$ and, inside, for $j=i+1,\dots,n$, it swaps $a[i]$ and $a[j]$ if $a[i]>a[j]$. Which statement on its key comparisons and swaps is correct?
Exactly $\frac{n(n-1)}{2}$ comparisons on every input; from $0$ swaps (sorted array) to $\frac{n(n-1)}{2}$ (distinct decreasing keys).
From $n-1$ comparisons (sorted array) to $\frac{n(n-1)}{2}$ (decreasing keys); at most $n-1$ swaps on every input.
Exactly $\frac{n(n-1)}{2}$ comparisons and exactly $\frac{n(n-1)}{2}$ swaps, whatever the initial order of the keys.
Exactly $\frac{n(n-1)}{2}$ comparisons on every input; at most $n-1$ swaps, one per iteration of the outer loop.
Explanation. Each pair $i<j$ is compared exactly once: $\sum_{i=1}^{n-1}(n-i)=\frac{n(n-1)}{2}$ comparisons. Each comparison causes at most one swap; none if the array is sorted, all of them if the keys are distinct and decreasing. At most $n-1$ swaps is the property of SelectionSort.
ExchangeSort (for $i=1,\dots,n-1$ and $j=i+1,\dots,n$, it swaps $a[i]$ and $a[j]$ if the key of $a[i]$ is larger than that of $a[j]$) is run on records (key, label): $[(2,A),(2,B),(1,C)]$. What is the final array?
$[(1,C),(2,A),(2,B)]$
$[(2,A),(2,B),(1,C)]$
$[(2,B),(1,C),(2,A)]$
$[(1,C),(2,B),(2,A)]$
Explanation. With $i=1$: $j=2$ does not swap ($2>2$ is false), $j=3$ swaps $(2,A)$ with $(1,C)$, giving $[(1,C),(2,B),(2,A)]$; with $i=2$ the comparison $2>2$ is false. The records with key $2$ come out in the order $B,A$: ExchangeSort is not stable.
We sort $a=[8,7,6,5,4,3,2,1]$ in increasing order. InsertionSort shifts to the right the keys larger than $\mathit{key}$; ExchangeSort swaps $a[i]$ and $a[j]$ for every pair $i<j$ with $a[i]>a[j]$; SelectionSort swaps $a[i]$ with the minimum of $a[i..n]$ only if it is in another position. How many shifts, swaps and swaps do they perform, respectively?
$28$, $28$ and $7$
$28$, $28$ and $4$
$28$, $28$ and $28$
$7$, $28$ and $4$
Explanation. On the decreasing array InsertionSort and ExchangeSort reach the maximum $\frac{8\cdot 7}{2}=28$. SelectionSort swaps $8\leftrightarrow 1$, $7\leftrightarrow 2$, $6\leftrightarrow 3$, $5\leftrightarrow 4$ and then finds every minimum already in place: $4$ swaps, fewer than the worst case $n-1=7$.
The sorting problem asks to rearrange an array $a[1..n]$ of natural numbers. Which condition must hold at the end?
$a[1]<a[2]<\dots<a[n]$
$a[1] \le a[2] \le \dots \le a[n]$, with the same elements as before (a permutation)
$a[1]$ is the minimum and $a[n]$ the maximum, the rest anything
Equal elements have been removed
Explanation. The order is nondecreasing (duplicates are allowed) and the final array is a permutation of the initial one. Strictly increasing order would be impossible with repeated elements.
A sorting algorithm is comparison-based if it accesses the keys only by comparing them in pairs and copying them. Which statement is correct?
Every sorting algorithm is comparison-based
A comparison-based algorithm cannot copy the keys
Comparison-based algorithms work only on natural numbers
The chapter's three sorts are; using digits as indices is not
Explanation. The three algorithms of the chapter use only comparisons and copies; using the value of a key as an index (as in counting sort) leaves the model. The model works for any comparable type.
A comparison-based sorting algorithm accesses the keys only by comparing them in pairs and copying them. Which operation on the keys is forbidden to it?
Using the value of a key as an array index
Evaluating $a[i]<a[j]$ to decide the order
Copying $a[i]$ into a variable $\mathit{tmp}$
Swapping $a[i]$ and $a[j]$ with three assignments
Explanation. Indexing by the value of a key (or doing arithmetic on it) is neither a comparison nor a copy. Comparisons, copies and swaps (three copies) are the allowed operations.
A comparison-based sorting algorithm performs, on some input, $10$ key comparisons and $7$ swaps (each swap uses a variable $\mathit{tmp}$). How many key assignments does it perform?
$14$
$7$
$21$
$31$
Explanation. A swap is three assignments ($\mathit{tmp}:=a[i]$, $a[i]\leftarrow a[j]$, $a[j]\leftarrow\mathit{tmp}$), so $3\cdot 7=21$. Comparisons are not assignments: $31$ adds them.
Sorting algorithms are evaluated by counting key comparisons and key assignments. Why are these numbers given in the best case and in the worst case?
Because they also depend on the initial order of the keys, not only on $n$
Because they depend on the speed of the computer
Because for sorting the average case is not defined
Because they depend only on $n$, and two cases suffice to check it
Explanation. For fixed $n$, different inputs give different counts (for instance Insertion Sort on a sorted or a decreasing array): the best and worst cases are the minimum and maximum over all inputs of size $n$.
A sort is in-place if the extra memory it uses is constant. An algorithm copies the $n$ keys into a new array $b[1..n]$, sorts $b$ and then copies $b$ back into $a$. Is it in-place?
Yes: at the end the result is in the original array
No: the extra memory grows with $n$
Yes: it uses only one extra variable, the array $b$
It depends on the number of comparisons it performs
Explanation. Array $b$ takes space proportional to $n$, so the extra memory is not constant. What counts is the space used, not where the result ends up.
Records (grade, name): $(28,\mathrm{Bea}),(30,\mathrm{Ada}),(28,\mathrm{Ale}),(30,\mathrm{Cle})$. They are sorted first by name (alphabetical order) and then, with a stable algorithm, by increasing grade. What is the final order?
Explanation. After the first sort: Ada, Ale, Bea, Cle. The stable sort by grade keeps this order among equal grades: for equal grades the names stay alphabetical.
InsertionSort, for $i=2,\dots,n$, sets $\mathit{key}=a[i]$, $j=i-1$ and, while $j\ge 1$ and $a[j]>\mathit{key}$, moves $a[j]$ to $a[j+1]$ and decrements $j$; then it sets $a[j+1]=\mathit{key}$. Counting the comparisons $a[j]>\mathit{key}$ and the shifts, what does it perform on $[2,3,4,5,1]$?
$4$ comparisons and $4$ shifts
$10$ comparisons and $4$ shifts
$7$ comparisons and $5$ shifts
$7$ comparisons and $4$ shifts
Explanation. For $i=2,3,4$ one false comparison suffices. For $i=5$ ($\mathit{key}=1$) the comparisons with $5,4,3,2$ are true: $4$ shifts, then $j=0$ ends the loop with no comparison. Total $3+4=7$ comparisons. The final assignment of $\mathit{key}$ is not a shift.
ExchangeSort, for $i=1,\dots,n-1$ and, inside, for $j=i+1,\dots,n$, swaps $a[i]$ and $a[j]$ if $a[i]>a[j]$. How many comparisons and swaps does it perform on $[3,1,2,0]$?
$6$ comparisons and $1$ swap
$6$ comparisons and $5$ swaps
$6$ comparisons and $6$ swaps
$3$ comparisons and $3$ swaps
Explanation. $i=1$: $[1,3,2,0]$, then $[0,3,2,1]$ ($2$ swaps). $i=2$: $[0,2,3,1]$, $[0,1,3,2]$ ($2$). $i=3$: $[0,1,2,3]$ ($1$). The comparisons are always $\frac{4\cdot 3}{2}=6$. A single swap is what Selection Sort would do.
ExchangeSort sorts $a[1..n]$: for $i=1,\dots,n-1$ it compares $a[i]$ with every $a[j]$, $j>i$, and swaps them if $a[i]>a[j]$. What holds after iteration $i$ of the outer loop?
$a[1..i]$ is sorted but may not hold the smallest keys
$a[n-i+1..n]$ holds the $i$ largest keys
$a[i..n]$ is sorted
$a[1..i]$ holds the $i$ smallest keys, sorted
Explanation. At the end of iteration $i$, $a[i]=\min(a[i..n])$; by induction $a[1..i]$ holds the $i$ smallest keys in order. An arbitrary sorted prefix is instead the property of Insertion Sort.
SelectionSort, for $i=1,\dots,n-1$, finds the index $\mathit{minIdx}$ of the minimum of $a[i..n]$ and swaps $a[i]$ and $a[\mathit{minIdx}]$ if $\mathit{minIdx}\ne i$. How many swaps does it perform on $[2,3,4,5,1]$?
$1$
$4$
$10$
$3$
Explanation. $[1,3,4,5,2]$, $[1,2,4,5,3]$, $[1,2,3,5,4]$, $[1,2,3,4,5]$: one swap for each of the $n-1=4$ iterations, the maximum possible. $10=\frac{5\cdot 4}{2}$ is the number of comparisons.
An already sorted array of $n=100$ distinct keys is sorted. How many key comparisons do Insertion Sort, Exchange Sort and Selection Sort perform, in this order?
$99$, $99$, $99$
$4950$, $4950$, $4950$
$99$, $4950$, $4950$
$99$, $4950$, $99$
Explanation. Insertion Sort makes one comparison for each $i=2,\dots,n$: $n-1=99$. Exchange and Selection Sort always compare every pair: $\frac{100\cdot 99}{2}=4950$.
The keys are very large records, so each key assignment costs much more than a comparison. Among Insertion, Exchange and Selection Sort, which guarantees the fewest assignments in the worst case?
Selection Sort: at most $n-1$ swaps, that is $3(n-1)$ assignments
Insertion Sort: in the worst case it moves no key
Exchange Sort: at most $n-1$ swaps
They are equivalent: all make $\frac{n(n-1)}{2}$ assignments in the worst case
Explanation. Selection Sort makes at most one swap per iteration. In the worst case Insertion Sort makes $\frac{n(n-1)}{2}$ shifts and Exchange Sort $\frac{n(n-1)}{2}$ swaps.
InsertionSort shifts right the keys $a[j]>\mathit{key}$ (strict comparison). A variant uses $a[j]\ge\mathit{key}$. What changes?
It no longer sorts correctly
It makes fewer shifts
It becomes in-place, whereas before it was not
It still sorts, but it is no longer stable
Explanation. With $\ge$ a key equal to $\mathit{key}$ is shifted right and $\mathit{key}$ jumps ahead of it: the relative order of records with equal keys is reversed. Shifts increase.
LinearSearch compares $a[i]=m$ for $i=1,2,\dots,n$ and returns the first $i$ for which the comparison is true ($-1$ if none). It looks for $m$ in an array of $n=12$ elements where $m$ appears for the first time in position $7$ (and then also in position $10$). How many comparisons $a[i]=m$ does it perform?
$12$
$6$
$10$
$7$
Explanation. It compares $a[1],\dots,a[7]$: the seventh comparison is true and the algorithm returns $7$ without looking at the rest. $12$ comparisons are needed only if $m$ is absent.
BinarySearch looks for $m$ in a sorted array $a[1..n]$: at each iteration of the while loop it examines the central element $a[mid]$ of the interval $[left,right]$ and, if it is not $m$, continues in the left or right half. At most how many iterations does it execute with $n=100$?
$6$
$7$
$8$
$50$
Explanation. The bound is $\lfloor\log_2 n\rfloor+1$; since $2^6=64\le 100<128$, $\lfloor\log_2 100\rfloor=6$, hence $7$ iterations.
BinarySearch looks for $m$ in $a[1..n]$ comparing $m$ with the central element $a[mid]$ and discarding the left half if $a[mid]<m$, the right half if $a[mid]>m$. Which assumption on the input is needed for it to be correct?
The array is sorted in non-decreasing order.
The elements of the array are all distinct.
The number $n$ of elements is a power of $2$.
The target value $m$ is in the array.
Explanation. Only sortedness is needed: if $a[mid]<m$, all elements in positions $\le mid$ are $<m$ and can be discarded. With repeated values the algorithm is still correct, and if $m$ is absent it returns $-1$.
In BinarySearch the search interval is $a[left..right]$ and the central index $mid$ is examined, rounded down when there are two central ones. In an iteration we have $left=4$ and $right=9$. Which index $mid$ is examined?
$7$
$5$
$6$
$6.5$
Explanation. $mid=left+\lfloor(right-left)/2\rfloor=4+\lfloor 5/2\rfloor=6$: the floor makes $mid$ an integer index, the leftmost of the two central ones.
Which statement about the number of iterations of BinarySearch, on a sorted array of $n\ge 1$ elements, is correct?
The while loop executes at most $\lfloor\log_2 n\rfloor+1$ iterations.
The while loop executes exactly $\lceil\log_2 n\rceil$ iterations on every input.
The while loop executes at most $\log_2 n$ iterations.
The while loop executes at most $n/2$ iterations.
Explanation. This is Observation 4.4. The number depends on the input (if $a[mid]=m$ at the first iteration one iteration is enough), and $\log_2 n$ is not enough: with $n=3$ and $m>a[3]$ two iterations are needed, while $\log_2 3<2$.
Which fact is the proof of the bound $\lfloor\log_2 n\rfloor+1$ on the iterations of BinarySearch based on?
Since the array is sorted, $a[mid]$ is the median of the interval, and after $\log_2 n$ medians the element $m$ has always been found.
Linear search performs at most $n$ comparisons; binary search avoids half of them at each step, hence it performs at most $n/2$.
Each iteration that does not return keeps at most $\lfloor L/2\rfloor$ of the $L$ elements of the interval, and each iteration needs at least one element.
The elements of the array are distinct, so each comparison with $a[mid]$ excludes exactly half of the positions.
Explanation. With $L=right-left+1$ and $mid=left+\lfloor(L-1)/2\rfloor$, the new interval has $\lfloor(L-1)/2\rfloor$ or $\lceil(L-1)/2\rceil$ elements, at most $\lfloor L/2\rfloor$. Iteration $k+1$ happens only if $1\le n/2^k$, i.e., $k\le\log_2 n$.
In the search problem, given an array $a[1..n]$ of natural numbers and a value $m$, one returns an index $k$ with $a[k]=m$ if it exists, and $-1$ otherwise. Why exactly $-1$?
Because $0$ is a valid index in pseudo-code, where the indices of an array start from $0$.
Because $-1$ signals that $m$ is smaller than all the elements, hence that it cannot be present.
Because binary search, when the interval becomes empty, always returns the value $mid-1$.
Because $-1$ is never a valid index, neither in pseudo-code (indices from $1$) nor in C++ (indices from $0$).
Explanation. The value returned when $m$ is missing must be distinguishable from every possible index: $-1$ is not an index in either indexing convention.
The search problem asks, given $a[1..n]$ and $m$, for an index $k$ with $a[k]=m$ if it exists, and $-1$ otherwise. With $a=[4,9,4,7]$ and $m=4$, which outputs are correct according to this definition?
Only $1$, the smallest index
Both $1$ and $3$
Only $3$, the last index
The number of occurrences, $2$
Explanation. The definition asks for an index $k$ with $a[k]=m$, any of them: $a[1]=a[3]=4$. LinearSearch returns $1$ because it stops at the first occurrence, but $3$ also solves the problem.
LinearSearch$(a,n,m)$ sets $i:=1$ and, while $i\le n$, returns $i$ if $a[i]=m$, otherwise executes $i\leftarrow i+1$; after the loop it returns $-1$. With $a=[4,2,7,1,5,9,3]$ and $m=6$, how many comparisons $a[i]=m$ does it perform and with which value of $i$ does the loop end?
$7$ comparisons; the loop ends with $i=8$ and returns $-1$
$7$ comparisons; the loop ends with $i=7$ and returns $-1$
$8$ comparisons; the loop ends with $i=8$ and returns $-1$
$6$ comparisons; the loop ends with $i=7$ and returns $-1$
Explanation. $6$ is not in the array: $a[i]=m$ is compared for $i=1,\dots,7$, all false, and the loop exits when $i=n+1=8$ (the condition $8\le 7$ is evaluated but there is no eighth comparison).
LinearSearch$(a,n,m)$ compares $a[i]=m$ for $i=1,2,\dots$ and returns the first $i$ for which it is true, or $-1$. Which statement on the number of comparisons is correct?
It always performs $n$ comparisons, because it scans the whole array, and returns the last index $k$ with $a[k]=m$.
If $k$ is the smallest index with $a[k]=m$ it performs $k-1$ comparisons, because $a[k]$ is recognized without comparing it.
If $k$ is the smallest index with $a[k]=m$ it performs exactly $k$ comparisons and returns $k$; if $m$ is absent it performs $n$.
It performs at most $\lfloor\log_2 n\rfloor+1$ comparisons if the array is sorted, and $n$ comparisons otherwise.
Explanation. $i$ takes the values $1,2,\dots$ and for each $i\le n$ one comparison is made: the algorithm stops at the first $k$ with $a[k]=m$ (after $k$ comparisons), or all $n$ elements are compared. Sortedness does not help linear search.
BinarySearch looks for $m$ in a sorted $a[1..n]$: with $left=1$, $right=n$, while $left\le right$ it examines $mid=left+\lfloor(right-left)/2\rfloor$, returns $mid$ if $a[mid]=m$, otherwise continues to the right ($a[mid]<m$) or to the left. With $a=[2,5,5,5,5,8,9]$ and $m=5$, what does it return?
$2$
$5$
$3$
$4$
Explanation. The first $mid$ is $1+\lfloor 6/2\rfloor=4$ and $a[4]=5$: the algorithm returns $4$ at once. Binary search returns an index of $m$, not necessarily the first occurrence ($2$).
BinarySearch (with $left=1$, $right=n$; while $left\le right$ it examines $mid=left+\lfloor(right-left)/2\rfloor$; it returns $mid$ if $a[mid]=m$, sets $left\leftarrow mid+1$ if $a[mid]<m$ and $right\leftarrow mid-1$ if $a[mid]>m$; at the end it returns $-1$) is run by mistake on the unsorted array $a=[7,3,9,1,5]$ with $m=3$. What does it return?
$2$
$-1$
$1$
$3$
Explanation. $mid=3$: $a[3]=9>3$, so $right=2$; $mid=1$: $a[1]=7>3$, so $right=0$ and the loop ends with $-1$, although $a[2]=3$. Without sortedness, discarding a half may discard $m$ itself.
For the problem of searching $m$ in $a[1..n]$ the notes present linear search and binary search. Which can be used on an unsorted array?
Only binary search: it halves the interval anyway
Both, and they return the same index
Only linear search: binary search needs a sorted array
Neither: the array must always be sorted first
Explanation. Linear search compares $m$ with every element and works on any array. Binary search discards half of the array according to the comparison with $a[mid]$, which is correct only if the array is sorted.
An algorithm for the search problem receives $a[1..n]$ and $m$ and returns a value $k$. Which condition says that the result is correct?
If $k\ne -1$ then $a[k]=m$; if $k=-1$, $m$ is not in $a$
$k$ is the smallest index with $a[k]=m$, or $-1$
$a[k]=m$ or $a[k]$ is the value closest to $m$
$k\ge 1$ and $a[k]=m$, whatever the input
Explanation. The definition asks for any index with $a[k]=m$ if one exists, and $-1$ otherwise. Returning the smallest index is a property of LinearSearch, not a requirement of the problem.
LinearSearch$(a,n,m)$ compares $a[i]=m$ for $i=1,2,\dots$ and returns the first $i$ for which the comparison is true, or $-1$. How many comparisons does it make in the worst case, and when?
$n+1$, when $m$ is absent (one more to exit)
$n$, when $m$ is absent or occurs only in $a[n]$
$n/2$, when $m$ is in the middle of the array
$n-1$, when $m$ does not occur in the array
Explanation. Each element is compared at most once; all $n$ comparisons are needed if the first occurrence is at position $n$ or there is none. The loop test $i\le n$ is not a key comparison.
BinarySearch (with $left=1$, $right=n$; while $left\le right$ it examines $mid=left+\lfloor(right-left)/2\rfloor$, returns $mid$ if $a[mid]=m$, sets $right=mid-1$ if $a[mid]>m$, $left=mid+1$ otherwise; then $-1$) is run on the UNSORTED array $[5,1,4,2,3]$ with $m=1$. What does it return?
$2$, the position of $1$
$1$, since $a[1]>m$
The loop does not terminate
$-1$, even though $a[2]=1$
Explanation. $mid=3$: $a[3]=4>1$, $right=2$. $mid=1$: $a[1]=5>1$, $right=0$. The loop ends and returns $-1$. Without the sorted-array hypothesis, discarding the right half can remove the searched value; the loop still terminates because the interval shrinks.
LinearSearch$(a,n,m)$ compares $a[i]=m$ for $i=1,2,\dots$ and stops at the first true comparison. All the $10$ elements of an array $a[1..10]$ of distinct values are searched one at a time. How many comparisons are made in total?
$100$
$55$
$45$
$10$
Explanation. The value at position $k$ is found after $k$ comparisons, so the total is $1+2+\dots+10=\frac{10\cdot 11}{2}=55$. $100$ always assumes the worst case, $45$ forgets the last comparison of each search.
BinarySearch performs at most $\lfloor\log_2 n\rfloor+1$ iterations because it examines the middle element. A variant always examines $mid=left$ (the first element of the interval). How many iterations can it need, in the worst case?
$\lfloor\log_2 n\rfloor+1$
$n$
$n/2$
$1$
Explanation. Each iteration discards one element instead of half the interval: it becomes a linear search. The logarithmic bound uses the hypothesis that $mid$ splits the interval in half.
In the division with remainder of $n=47$ by $b=5$, what are the quotient and the remainder?
$q=9$, $r=3$
$q=9$, $r=2$
$q=10$, $r=-3$
$q=8$, $r=7$
Explanation. $47=9\cdot 5+2$ with $0\le 2<5$: $q=\lfloor 47/5\rfloor=9$ and $r=47\bmod 5=2$. Quotient and remainder are unique precisely because of the constraint $0\le r<b$.
Let $n=(2731)_8$. What are $n\bmod 8$ and $\lfloor n/8\rfloor$?
$n\bmod 8=2$ and $\lfloor n/8\rfloor=(731)_8$
$n\bmod 8=1$ and $\lfloor n/8\rfloor=(2730)_8$
$n\bmod 8=31$ and $\lfloor n/8\rfloor=(27)_8$
$n\bmod 8=1$ and $\lfloor n/8\rfloor=(273)_8$
Explanation. By Observation 5.2 the remainder of the division by the base is the least significant digit $d_0$, and the quotient is obtained by removing $d_0$: this is the principle of ChangeOfBase.
PrimalityTest$(n)$ tries the divisors $d=2,3,\dots,\lfloor\sqrt n\rfloor$ and stops at the first one that divides $n$. How many values of $d$ does it try on the prime number $n=97$?
$9$
$8$
$47$
$95$
Explanation. $\lfloor\sqrt{97}\rfloor=9$, hence $d=2,3,\dots,9$: $8$ values, none of which divides $97$. BasicPrimalityTest would try $d=2,\dots,\lfloor 97/2\rfloor=48$, i.e., $47$ values.
The sieve of Eratosthenes, for every prime $p\le\lfloor\sqrt n\rfloor$, marks as composite the multiples $j=p^2,\,p^2+p,\dots\le n$. Why can the inner loop for $p$ start from $j:=p^2$?
Because the multiples of $p$ smaller than $p^2$ are all prime numbers.
Because $p^2$ is the smallest composite number smaller than $n$.
To avoid marking $p$ itself; starting from $2p$ would give the same number of assignments.
Because every multiple $m$ of $p$ with $p<m<p^2$ has a divisor $d$ with $2\le d<p$, hence it has already been marked by a smaller prime.
Explanation. This is the fact that $m=d\,p$ with $2\le d<p$, and $m$ is a multiple of the smallest prime dividing $d$. Starting from $2p$ would give the same result but with useless assignments.
Two natural numbers are coprime if their only common positive divisor is $1$. Which pair consists of coprime numbers?
$15$ and $28$
$21$ and $35$
$12$ and $18$
$14$ and $49$
Explanation. Two numbers are coprime if $\gcd(n,m)=1$: $15=3\cdot5$ and $28=2^2\cdot 7$ share no divisor other than $1$. The other pairs have $\gcd$ equal to $7$, $6$ and $7$.
Which statement about the divisors of composite natural numbers is correct?
Every composite number $n\ge 2$ has a divisor $d$ with $\lfloor\sqrt n\rfloor<d\le n/2$.
Every composite number $n\ge 2$ has exactly one divisor $d$ with $2\le d\le\sqrt n$.
A number $n\ge 2$ with no divisor in $\{2,\dots,\lfloor\sqrt n\rfloor\}$ is composite.
Every composite number $n\ge 2$ has a divisor $d$ with $2\le d\le\lfloor\sqrt n\rfloor$.
Explanation. A divisor in $(\lfloor\sqrt n\rfloor,n/2]$ is missing for $n=4$, «exactly one divisor» is false for $n=12$ ($2$ and $3$), and an $n$ with no divisor up to $\lfloor\sqrt n\rfloor$ is not composite: the Corollary says exactly that such an $n$ is prime.
Which results are used to prove Corollary 5.8 (every composite $n$ has a divisor $d$ with $2\le d\le\lfloor\sqrt n\rfloor$)?
A divisor $d<n$ satisfies $d\le n/2$; and $\gcd(n,m)=\gcd(m,n\bmod m)$ holds.
If $d$ divides $n$ then $n/d$ divides $n$; and if $d>\sqrt n$ then $n/d<\sqrt n$.
The multiples of a prime $p$ between $p$ and $p^2$ have a divisor smaller than $p$.
Quotient and remainder of the division are unique; and $n\bmod b$ is the last digit of $n$ in base $b$.
Explanation. Start from a divisor $2\le d\le n-1$: if $d\le\sqrt n$ we are done, otherwise $n/d$ is a divisor (5.6) smaller than $\sqrt n$ (5.7) and at least $2$ since $d<n$.
SieveOfEratosthenes$(n)$ marks as composite, for every prime $p=2,3,\dots$, the multiples $p^2,p^2+p,\dots\le n$. Which result guarantees that the outer loop can stop at $p=\lfloor\sqrt n\rfloor$ without leaving composites marked as primes?
The multiples of $p$ smaller than $p^2$ have already been marked.
The remainder of the division by the base is the last digit.
For every pair $n,m\ge 1$ we have $\gcd(n,m)=\gcd(m,n\bmod m)$.
Every composite $m\le n$ has a prime divisor $q\le\lfloor\sqrt n\rfloor$.
Explanation. Every composite $m\le n$ is marked by the inner loop of its smallest prime divisor, which is at most $\lfloor\sqrt n\rfloor$. The fact that the multiples of $p$ smaller than $p^2$ are already marked justifies instead the starting point $j=p^2$.
Let $n\ge 1$ have representation $(d_{k-1}\dots d_1d_0)_b$ in base $b\ge 2$ ($d_0$ is the least significant digit). Which statement on $n\bmod b$ and $\lfloor n/b\rfloor$ is correct?
$n\bmod b=d_{k-1}$ and $\lfloor n/b\rfloor=(d_{k-2}\dots d_0)_b$
$n\bmod b=d_0$ and $\lfloor n/b\rfloor=(d_{k-1}\dots d_1 0)_b$
$n\bmod b=d_0\,b$ and $\lfloor n/b\rfloor=(d_{k-1}\dots d_1)_b$
$n\bmod b=d_0$ and $\lfloor n/b\rfloor=(d_{k-1}\dots d_1)_b$
Explanation. $n=b\cdot\sum_{i\ge 1}d_ib^{i-1}+d_0$ with $0\le d_0<b$: by the uniqueness of quotient and remainder, the remainder is the last digit and the quotient is the number formed by the remaining digits. This is the fact behind the change of base.
A first primality test for $n\ge 2$ tries the divisors $d=2,3,\dots,\lfloor n/2\rfloor$. Which fact guarantees that the values between $\lfloor n/2\rfloor+1$ and $n-1$ need not be tried?
Every divisor $d$ of $n$ with $d<n$ satisfies $d\le\sqrt n$, because $d\cdot d\le n$.
Every divisor $d$ of $n$ with $d<n$ satisfies $d\le n/2$, because $n=k\,d$ with $k\ge 2$.
If $n$ is composite, then $\lfloor n/2\rfloor$ is always a divisor of $n$.
Every even number larger than $2$ is composite, so half of the values suffice.
Explanation. If $d$ divides $n$ and $d<n$, then $n=k\,d$ with $k\ge 2$ and $d=n/k\le n/2$. The bound $\sqrt n$ holds for the smallest divisor of a composite number, not for all divisors (for instance $6$ divides $12$ and $6>\sqrt{12}$).
How does one prove that $\gcd(n,m)=\gcd(m,\,n\bmod m)$ for $n,m\ge 1$ ($\gcd$: greatest common divisor)?
By induction on $n$, using only the fact that $n\bmod m<n$ and that the greatest common divisor of $n$ and $0$ is $n$.
One uses that every composite number has a divisor $d$ with $2\le d\le\lfloor\sqrt n\rfloor$, applied first to $n$ and then to $m$.
One shows that $(n,m)$ and $(m,\,n\bmod m)$ have the same common divisors, using $n\bmod m=n-q\,m$ with $q=\lfloor n/m\rfloor$.
One shows that $n\bmod m$ always divides $n$, so every divisor of $n\bmod m$ is also a common divisor of $n$ and $m$.
Explanation. If $d$ divides $n$ and $m$, it also divides $n-qm=n\bmod m$; conversely, if it divides $m$ and $n\bmod m$, it divides $qm+(n\bmod m)=n$. The sets of common divisors coincide, hence so do their maxima.
A natural number $n \ge 2$ is prime if its only divisors are $1$ and $n$. Which statement is correct?
$1$ is not prime, and $2$ is the only even prime
$1$ is prime, since it is divisible only by $1$ and itself
$9$ is prime, since it is odd
$0$ is prime
Explanation. The definition requires $n \ge 2$, so $0$ and $1$ are not prime; every even number larger than $2$ has the divisor $2$; $9=3 \cdot 3$ is composite.
The primality test checks divisors only up to $\sqrt{n}$. Which fact, together with «if $d>\sqrt{n}$ then $n/d<\sqrt{n}$», justifies it?
Every composite number is even
There are infinitely many primes
If $d$ divides $n$, so does $n/d$
$\sqrt{n}$ is always an integer
Explanation. A divisor $d>\sqrt{n}$ has the companion $n/d<\sqrt{n}$, which the test would already have found. The other statements are false or not needed.
A natural number $m$ is a multiple of $p \ge 1$ if there is $k \in \N$ with $m=k\,p$. Which statement is correct?
$0$ is a multiple of no number
$p$ is not a multiple of itself
The multiples of $3$ below $10$ are only $3,6,9$, since $0$ is excluded
$0$ is a multiple of every $p \ge 1$
Explanation. With $k=0$ we get $0=0 \cdot p$: zero is a multiple of every $p$. With $k=1$, $p$ is a multiple of itself; the multiples of $3$ below $10$ are $0,3,6,9$.
The greatest common divisor $\gcd(n,m)$ of two naturals $n,m \ge 1$ is the largest common divisor. What is $\gcd(84,36)$?
$6$
$12$
$4$
$252$
Explanation. $84=2^2 \cdot 3 \cdot 7$ and $36=2^2 \cdot 3^2$: the common factors give $2^2 \cdot 3=12$. $6$ is a common divisor but not the largest; $252$ is the least common multiple.
ChangeOfBase$(n,b)$ repeats, while $n>0$: $d[k]\leftarrow n\bmod b$, $n\leftarrow\lfloor n/b\rfloor$, $k\leftarrow k+1$ (with $k$ starting at $1$); it returns $d$ and the number of digits $nd$. What does it return with $n=45$, $b=4$?
$d=[2,3,1]$, $nd=3$
$d=[1,3,2,0]$, $nd=4$
$d=[1,3,2]$, $nd=3$
$d=[3,2,1]$, $nd=3$
Explanation. $45\bmod 4=1$, $\lfloor 45/4\rfloor=11$; $11\bmod 4=3$, $\lfloor 11/4\rfloor=2$; $2\bmod 4=2$, then $n=0$. So $45=(231)_4$, but $d$ stores the digits from the least significant one: $d=[1,3,2]$.
ChangeOfBase$(n,b)$ converts $n\ge 1$ to base $b\ge 2$ with one iteration of the while loop per digit (it divides $n$ by $b$ while $n>0$). How many iterations does it run with $n=1000$ and $b=10$?
$4$
$3$
$5$
$10$
Explanation. The digits are $\lfloor\log_{10}1000\rfloor+1=4$: $1000\to 100\to 10\to 1\to 0$. $3=\log_{10}1000$ forgets the $+1$.
BasicPrimalityTest$(n)$ tries the candidate divisors $d=2,3,\dots,\lfloor n/2\rfloor$ and returns false at the first $d$ with $n\bmod d=0$. How many candidates does it try with $n=49$ and with $n=31$?
$23$ and $14$
$6$ and $15$
$6$ and $14$
$7$ and $30$
Explanation. $n=49$: it stops at $d=7$, after trying $2,\dots,7$ ($6$ values). $n=31$ is prime: it tries all $d=2,\dots,15$, that is $14$ values.
SieveOfEratosthenes$(n)$ runs $p=2,3,\dots,\lfloor\sqrt n\rfloor$ and, if $p$ is not yet marked as composite, marks the multiples $p^2,p^2+p,\dots\le n$. With $n=30$, for which values of $p$ does it mark multiples?
$2$, $3$ and $5$
$2$, $3$, $5$, $7$, $11$ and $13$
$2$, $3$, $4$ and $5$
$2$ and $3$
Explanation. $\lfloor\sqrt{30}\rfloor=5$, so $p$ takes the values $2,3,4,5$; $4$ is already marked (a multiple of $2$) and is skipped. Primes above $5$ are not needed: every composite $\le 30$ has a prime divisor $\le 5$.
EuclideanAlgorithm$(n,m)$: while $m\ne 0$, it sets $r:=n\bmod m$, $n\leftarrow m$, $m\leftarrow r$; then it returns $n$. How many loop iterations does it run with $(n,m)=(195,84)$, and what does it return?
$2$ iterations, returns $27$
$3$ iterations, returns $27$
$4$ iterations, returns $1$
$3$ iterations, returns $3$
Explanation. $(195,84)\to(84,27)\to(27,3)\to(3,0)$: three iterations, and $\gcd(195,84)=3$. $27$ is an intermediate remainder, not the greatest common divisor.
EuclideanAlgorithm$(n,m)$ (while $m\ne 0$: $r:=n\bmod m$, $n\leftarrow m$, $m\leftarrow r$; then it returns $n$) is called with $n<m$, for instance $(12,30)$. What happens?
The loop does not terminate, since $m$ does not decrease
The first iteration swaps them, $(30,12)$, and it goes on
It returns $12$ at once, the smaller number
A check must be added to order the two numbers
Explanation. If $n<m$ then $n\bmod m=n$, and $(n,m)$ becomes $(m,n)$. Then $(30,12)\to(12,6)\to(6,0)$: it returns $6$. The hypothesis $n\ge m$ is not needed.
Two natural numbers are coprime if their greatest common divisor is $1$. What is $\gcd(n,n+1)$ for every $n\ge 1$?
$n$, because $n$ divides both $n$ and $n+1$
$2$ if $n$ is even, $1$ if $n$ is odd
It depends on $n$: it must be computed case by case
$1$: a common divisor also divides the difference, $1$
Explanation. If $d$ divides $n$ and $n+1$, it divides $(n+1)-n=1$, so $d=1$: two consecutive integers are always coprime. Euclid confirms it: $(n+1,n)\to(n,1)\to(1,0)$.
ChangeOfBase$(n,b)$ requires a base $b\ge 2$: while $n>0$ it stores the digit $n\bmod b$ and then $n\leftarrow\lfloor n/b\rfloor$. What would happen calling it with $n=5$ and $b=1$?
$\lfloor n/1\rfloor=n$: $n$ does not decrease and the loop never ends
It returns five digits equal to $1$ (unary notation)
It returns a single digit, equal to $5$
It returns zero digits, because $5\bmod 1=0$
Explanation. With $b=1$ every remainder is $0$ and the quotient is $n$ itself, so the condition $n>0$ stays true forever (and $\lfloor\log_1 n\rfloor+1$ is undefined too). With $b\ge 2$ instead $\lfloor n/b\rfloor<n$ and the loop terminates.
The sieve of Eratosthenes marks, for each prime $p$, the multiples starting from $p^2$. If it started from $2p$ instead, what would change?
The result is the same, with extra work
It would also mark some primes as composite
It would leave some composites unmarked
The loop would not terminate
Explanation. The multiples $kp$ with $k<p$ have a prime divisor smaller than $p$, so they are already marked: starting from $2p$ marks them again, with no errors. Starting from $p^2$ is an optimisation.
The primality test tries the divisors $d=2,\dots,\lfloor\sqrt n\rfloor$. A variant stops at $\lfloor\sqrt n\rfloor-1$. On which input is it wrong?
On $n=48$, which it declares prime
On $n=47$, which it declares composite
On $n=49$, which it declares prime
On no input
Explanation. $\lfloor\sqrt{49}\rfloor-1=6$: the variant tries $2,\dots,6$, none divides $49$, and it declares it prime. The square of a prime has $\sqrt n$ as its only useful divisor; $48$ has the divisor $2$.
In C++, with <code>int a = 10, b = 3;</code>, what does <code>cout << a / b << " " << a % b;</code> print?
<code>3.33333 1</code>
<code>3 1</code>
<code>3 0.33333</code>
<code>4 1</code>
Explanation. Between two <code>int</code> values the operator <code>/</code> performs the integer division ($10/3$ gives $3$) and <code>%</code> gives the remainder ($1$).
In C++, with <code>int a = 10, b = 3;</code>, which expression gives the floating-point division, $3.33333$?
<code>(double)(a / b)</code>
<code>a / b</code>
<code>(double)a / b</code>
<code>a % b</code>
Explanation. The conversion must happen before the division: <code>(double)a / b</code> divides a <code>double</code> by an <code>int</code>. In <code>(double)(a / b)</code> the integer division already gives $3$, converted into $3.0$.
In C++, <code>incrementByValue(int x)</code> and <code>incrementByReference(int& x)</code> both execute <code>x = x + 1;</code>. After <code>int k = 5; incrementByValue(k); incrementByReference(k);</code> what is the value of <code>k</code>?
$6$
$5$
$7$
The program does not compile
Explanation. Passing by value changes only the local copy; passing by reference (<code>int&</code>) changes the caller's variable: a single increment, $k=6$.
In C++, what is the value of <code>(5 << 2) + (7 >> 1)</code>?
$23$
$13$
$34$
$23.5$
Explanation. A left shift by $k$ positions multiplies by $2^k$: $5\cdot 4=20$; a right shift by one position removes the least significant bit: $(111)_2\to(11)_2=3$. Total $23$.
In C++, after <code>int x = 5;</code>, what do <code>cout << ++x;</code>, <code>cout << x++;</code> and <code>cout << x;</code> print, in this order?
$6$, $7$, $7$
$6$, $6$, $7$
$5$, $6$, $7$
$6$, $6$, $6$
Explanation. The pre-increment <code>++x</code> increments and then returns the value ($6$); the post-increment <code>x++</code> returns the value ($6$) and then increments, so at the end $x=7$.
The program is executed by an interpreter instruction by instruction, with no compilation.
The execution starts from the first function written in the file.
Variables need not be declared: the data type is determined during the execution.
The <code>.cpp</code> source file is translated by a compiler into an executable file, and the execution starts from the function <code>main</code>.
Explanation. C++ is compiled (for instance with <code>g++</code>) and requires variables to be declared with their data type. The interpreter and dynamic typing are features of Python.
A single-line comment starts with <code>//</code>, a multi-line one lies between <code>/*</code> and <code>*/</code>; the compiler ignores them.
A single-line comment starts with <code>#</code>, a multi-line one lies between triple quotes; the compiler ignores them.
A single-line comment starts with <code>//</code> and, like every instruction, must end with the symbol <code>;</code>.
A multi-line comment is written only by repeating <code>//</code> on every line: the form <code>/* */</code> does not exist.
Explanation. In C++ <code>//</code> comments until the end of the line and <code>/* … */</code> encloses a multi-line comment; <code>#</code> and triple quotes are the conventions of Python.
In C++ (<code>cout</code> displays by default at most six significant digits), what does the following fragment print? <pre>bool b = false;
double x = 123456.789;
cout << b << " " << x;</pre>
<code>false 123456.789</code>
<code>0 123456.789</code>
<code>0 123457</code>
<code>false 123457</code>
Explanation. A false <code>bool</code> value is printed as <code>0</code>; the <code>double</code> is displayed with six significant digits, hence rounded to <code>123457</code> (the stored value does not change).
In C++ every variable must be declared with its data type before use. Which instruction correctly stores the single character A in a new variable?
<code>char c = 'A';</code>
<code>char c = "A";</code>
<code>c = 'A';</code>
<code>char c = A;</code>
Explanation. A <code>char</code> is written between single quotes. Between double quotes there is a string (data type <code>string</code>); without a data type the variable is not declared; without quotes <code>A</code> is the name of a variable.
In C++, with <code>using namespace std;</code>, what does <code>cout << "a" << 3 + 4 << "b" << endl;</code> print?
<code>a3+4b</code>
<code>a7b</code>
<code>a 7 b</code>
<code>a34b</code>
Explanation. The text between double quotes is printed as it is, the expression <code>3 + 4</code> is evaluated ($7$), and the operator <code><<</code> adds no spaces between the values.
In a C++ program, what is needed to use <code>cout</code> and <code>endl</code> without the prefix <code>std::</code>?
Only <code>#include <iomanip></code>, which also contains <code>cout</code>
The instruction <code>import iostream;</code> at the beginning of the file
<code>#include <string></code> and the function <code>main</code>
<code>#include <iostream></code> and the instruction <code>using namespace std;</code>
Explanation. The input-output stream library is included with <code>#include <iostream></code>; <code>using namespace std;</code> avoids writing <code>std::cout</code> and <code>std::endl</code>. <code><iomanip></code> only gives manipulators such as <code>setprecision</code>.
In C++ the ternary operator <code>c ? x : y</code> evaluates to <code>x</code> if the condition <code>c</code> is true, otherwise to <code>y</code>. Which value does <code>g</code> receive? <pre>int score = 75;
string g = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" : "D";</pre>
<code>"C"</code>
<code>"B"</code>
<code>"D"</code>
<code>"A"</code>
Explanation. The conditions are evaluated from top to bottom: $75\ge 90$ and $75\ge 80$ are false, $75\ge 70$ is true, so <code>g</code> is <code>"C"</code>.
In C++, with <code>int n = 7;</code>, what does <code>cout << ((n % 2 == 0) ? n / 2 : 3 * n + 1);</code> print?
$3$
$3.5$
$22$
$21$
Explanation. $7\bmod 2=1$, so the condition is false and the third operand is evaluated: $3\cdot 7+1=22$. The second operand (integer division, $3$) is not evaluated.
In C++, in the following fragment, how many times is the condition <code>i <= 5</code> evaluated and what is <code>s</code> at the end? <pre>int i = 1, s = 0;
while (i <= 5)
{
s += i;
i++;
}</pre>
$6$ times, $s=15$
$5$ times, $s=15$
$6$ times, $s=21$
$5$ times, $s=10$
Explanation. The body is executed for $i=1,\dots,5$ and $s=1+2+3+4+5=15$; the condition is also evaluated a sixth time, with $i=6$, when it is false and the loop terminates.
In C++ <code>continue</code> skips the rest of the current iteration and <code>break</code> terminates the loop. What does the fragment print? <pre>for (int i = 1; i <= 10; i++)
{
if (i % 3 == 0) continue;
if (i > 7) break;
cout << i << " ";
}</pre>
<code>1 2 4 5 7 8</code>
<code>1 2 4 5 7 8 10</code>
<code>1 2 4 5 7</code>
<code>1 2 3 4 5 6 7</code>
Explanation. The multiples of $3$ are skipped by <code>continue</code>; with $i=8$ (not a multiple of $3$) the condition $i>7$ is true and <code>break</code> terminates the loop before printing.
In C++ the elements of an array of size $n$ are <code>b[0]</code>, …, <code>b[n-1]</code>. What does the fragment print? <pre>int b[] = {9, 12, 3, 16};
b[2] = 5;
cout << b[1] + b[2];</pre>
$14$
$17$
$15$
$21$
Explanation. <code>b[2] = 5</code> replaces the third element ($3$); then <code>b[1] + b[2]</code> $=12+5=17$. Counting the indices from $1$ would lead to $9+5=14$.
Which statement about dynamic-size arrays in C++ is correct?
They are allocated with <code>int* a = new int[n];</code> and their memory is freed automatically at the end of the loop that uses them.
They are declared with <code>int a[] = new int[n];</code> and their elements are indexed from $1$ to $n$, as in pseudo-code.
They require $n$ to be a constant written in the code: the size cannot be read as input during the execution.
They are allocated with <code>int* a = new int[n];</code>, with $n$ known only during the execution, and freed with <code>delete[] a;</code>.
Explanation. The pointer <code>a</code> stores the address of the first element; the elements go from <code>a[0]</code> to <code>a[n-1]</code>, and the memory allocated with <code>new</code> must be returned with <code>delete[]</code>.
In a C++ file the function <code>int addition(int a, int b)</code> is defined after <code>main</code>, without any previous declaration, and it is called inside <code>main</code>. What happens?
The program works: the compiler looks for the called function in the whole file, in any position.
Compilation error: a function must be defined (or declared) before the point where it is called.
The program works, but <code>addition</code> is executed before <code>main</code>, because it is written after it.
The program compiles, but the execution starts from <code>addition</code>, because it is the last function of the file.
Explanation. In C++ custom functions are written before <code>main</code> (or declared before it): the compiler must know them at the point of the call. The execution always starts from <code>main</code>.
FindMaximum in pseudo-code executes $max:=a[1]$ and «for $i:=2$ to $n$», with the array $a[1..n]$. In C++ the array has indices from $0$ to $n-1$. Which translation is correct?
<code>int max = a[1];</code> and <code>for (int i = 2; i <= n; i++)</code>
<code>int max = a[0];</code> and <code>for (int i = 1; i <= n; i++)</code>
<code>int max = a[0];</code> and <code>for (int i = 2; i < n; i++)</code>
<code>int max = a[0];</code> and <code>for (int i = 1; i < n; i++)</code>
Explanation. The index $i$ of the pseudo-code corresponds to <code>i-1</code> in C++: $a[1]$ becomes <code>a[0]</code> and the values $2,\dots,n$ become <code>1</code>, …, <code>n-1</code>. With <code>i <= n</code> the element <code>a[n]</code>, outside the array, would be read.
The C++ function <code>ArrayMaxValue(n, a)</code> sets <code>max = a[0]</code> and, for <code>i</code> from <code>1</code> to <code>n-1</code>, executes <code>max = a[i]</code> if <code>a[i] > max</code>. On <code>{9, 12, 3, 16, 19, 11, 12}</code> (with $n=7$), how many times does it execute the update <code>max = a[i]</code>?
$4$
$6$
$3$
$2$
Explanation. The current maximum goes from $9$ to $12$, then to $16$ and to $19$: three updates. The initialization <code>max = a[0]</code> is not an update, and the last $12$ does not exceed $19$.
In C++ the relational operators (<code>==</code>, <code>!=</code>, <code><</code>, <code><=</code>, <code>></code>, <code>>=</code>) compare two values. Which statement is correct?
They return a boolean value (<code>true</code> or <code>false</code>), and <code>=</code> is instead assignment
<code>=</code> and <code>==</code> are equivalent
They return the difference of the two operands
They can be used only between integers
Explanation. <code>a == b</code> is <code>true</code> if the values are equal; <code>a = b</code> assigns. Relational operators also work between reals and characters.
In C++ the logical operators are <code>&&</code> (and), <code>||</code> (or), <code>!</code> (not). Which statement is correct?
<code>&&</code> always evaluates both operands
They evaluate the second operand only if needed
<code>!</code> has two operands
<code>&&</code> and <code>&</code> are the same operator
Explanation. If the first operand of <code>&&</code> is false, the result is false without looking at the second (and symmetrically for <code>||</code> with true). <code>&</code> is bitwise AND.
In C++ every variable has a declared type. Which statement about types is correct?
A variable may change type during execution, as in Python
<code>int</code>s have unlimited precision
The type is only a comment
The type does not change, and an <code>int</code> has a bounded range
Explanation. C++ is statically typed: the compiler knows the type of every variable. A typical <code>int</code> has $32$ bits; Python integers, instead, have no fixed limit.
The C++ program is saved in the file <code>hello.cpp</code>. Which command compiles it producing the executable <code>hello</code>?
<code>g++ -o hello.cpp hello</code>
<code>python3 hello.cpp -o hello</code>
<code>g++ -o hello hello.cpp</code>
<code>javac -o hello hello.cpp</code>
Explanation. <code>g++</code> translates the source into an executable; <code>-o</code> is followed by the executable name, then by the source file. Swapping them would overwrite the source.
What happens when compiling this C++ program? <pre>#include <iostream>
using namespace std;
int main() {
cout << "Hi" << endl
return 0;
}</pre>
It compiles and prints <code>Hi</code>
Compilation error: a <code>;</code> is missing
It compiles and prints <code>Hi0</code>
It compiles with a warning, then prints <code>Hi</code>
Explanation. In C++ every statement ends with <code>;</code>: without it, the compiler reads <code>endl return 0</code> as one statement and reports an error.
In C++, what does the fragment print? <pre>int x = 3.9;
bool b = 5;
cout << x << " " << b;</pre>
<code>4 1</code>
<code>3.9 5</code>
<code>3 5</code>
<code>3 1</code>
Explanation. A real value assigned to an <code>int</code> loses its fractional part (truncation, not rounding); every non-zero value assigned to a <code>bool</code> becomes <code>true</code>, which <code>cout</code> prints as <code>1</code>.
In C++, with <code>#include <iomanip></code>, what does <code>cout << fixed << setprecision(2) << 3.14159;</code> print?
<code>3.1</code>
<code>3.14</code>
<code>3.14159</code>
<code>3.142</code>
Explanation. With <code>fixed</code>, <code>setprecision(k)</code> fixes the number of digits after the decimal point: two digits, rounded, give <code>3.14</code>. Without <code>fixed</code> it would count significant digits (<code>3.1</code>).
In C++ the manipulator <code>endl</code> is used with <code>cout</code>, as in <code>cout << n << endl;</code>. What does it do?
It ends the program after printing
It prints the word <code>endl</code>
It writes a newline only if the line is too long
It writes a newline and flushes the output buffer
Explanation. <code>endl</code> writes a newline and forces what is in the buffer to be written at once. With <code>using namespace std;</code> it is written without the prefix <code>std::</code>.
In C++, what is the value of <code>x</code> at the end? <pre>int x = 10;
x += 5;
x *= 2;
x -= 4;
x /= 3;</pre>
$8$
$8.67$
$9$
$26$
Explanation. $10\to 15\to 30\to 26\to\lfloor 26/3\rfloor=8$: <code>x /= 3</code> is <code>x = x / 3</code> between two <code>int</code>s, hence integer division (the fractional part is dropped, not rounded to $9$).
In C++, what is <code>a</code> after <code>int a = 5; a *= 2 + 3;</code>?
$13$
$10$
$25$
$15$
Explanation. <code>a *= e</code> is equivalent to <code>a = a * (e)</code>: the whole right-hand side is evaluated first, $2+3=5$, then $5\cdot 5=25$. $13$ is $5\cdot 2+3$.
In C++ <code>i++</code> returns the value of <code>i</code> and then increments it, <code>++i</code> increments it and then returns it. What does the fragment print? <pre>int i = 3;
int j = i++ + 2;
int k = ++i * 2;
cout << i << " " << j << " " << k;</pre>
<code>5 5 10</code>
<code>5 6 10</code>
<code>4 5 8</code>
<code>5 5 8</code>
Explanation. <code>j = 3 + 2 = 5</code> and then <code>i = 4</code>; <code>++i</code> brings <code>i</code> to $5$ and returns $5$, so <code>k = 10</code>.
In C++, what happens when running the fragment? <pre>int a = 5;
if (a = 0)
cout << "zero";
else
cout << "non zero";</pre>
It prints <code>zero</code>, and <code>a</code> is $0$
It prints <code>non zero</code>, and <code>a</code> is $5$
It prints <code>non zero</code>, and <code>a</code> is $0$
Compilation error
Explanation. <code>a = 0</code> is an assignment, not a comparison: it sets <code>a</code> to $0$ and its value is $0$, that is false, so the else branch runs. The comparison is written <code>a == 0</code>.
In C++ (<code>&&</code> and, <code>||</code> or, <code>!</code> not; <code>cout</code> prints booleans as $1$ and $0$), with <code>int a = 2, b = 5;</code>, what does <code>cout << (a > 1 && !(b == 5));</code> print?
<code>1</code>
<code>false</code>
<code>true</code>
<code>0</code>
Explanation. $a>1$ is true, $b==5$ is true and hence <code>!(b == 5)</code> is false: true and false gives false, printed as <code>0</code> (without <code>boolalpha</code>, <code>cout</code> does not write <code>false</code>).
In C++, what does the fragment print with <code>int x = -1;</code>? <pre>if (x > 0)
cout << "a";
cout << "b";</pre>
Nothing
<code>b</code>
<code>ab</code>
<code>a</code>
Explanation. Without braces the body of the if is only the first statement; indentation does not matter in C++. So <code>cout << "b";</code> always runs.
In C++, which character does <code>s</code> get with <code>int t = 25;</code>? <pre>char s;
if (t > 30) s = 'A';
else if (t > 20) s = 'B';
else if (t > 10) s = 'C';
else s = 'D';</pre>
<code>'B'</code>
<code>'C'</code>
<code>'D'</code>
<code>'A'</code>
Explanation. The conditions are checked in order and only the first true branch runs: $25>30$ is false, $25>20$ is true. $25>10$ is true too, but that branch is no longer considered.
In C++, what is <code>s</code> at the end? <pre>int n = 4096, s = 0;
while (n > 0) {
s += n % 10;
n /= 10;
}</pre>
$4$
$4096$
$19$
$15$
Explanation. <code>n % 10</code> is the last decimal digit and <code>n /= 10</code> removes it: the loop adds up the digits, $6+9+0+4=19$, and stops when <code>n</code> becomes $0$. $4$ is the number of iterations.
In C++, what does <code>for (int i = 10; i > 0; i -= 3) cout << i << " ";</code> print?
<code>10 7 4 1</code>
<code>10 7 4</code>
<code>7 4 1</code>
<code>10 7 4 1 -2</code>
Explanation. The initialisation gives $10$; after each iteration $i$ decreases by $3$ and the condition $i>0$ is checked before each iteration: $10,7,4,1$, then $-2$ makes it false.
In C++, what is <code>i</code> at the end? <pre>int i = 0;
while (true) {
i += 3;
if (i > 10) break;
}</pre>
$9$
$12$
$10$
The loop does not terminate
Explanation. <code>while (true)</code> is left only through <code>break</code>: $i=3,6,9,12$, and at $12>10$ it exits. $9$ is the last value not greater than $10$.
In C++, what does <code>int a[5] = {1, 2}; cout << a[1] + a[3];</code> print?
$3$
An unpredictable value
Compilation error
$2$
Explanation. When the brace initialiser has fewer values than the size, the remaining elements are $0$: $a=\{1,2,0,0,0\}$, and $a[1]+a[3]=2+0$. $3$ counts indices from $1$.
In C++ a dynamic $m\times n$ matrix is allocated with <code>int** matrix = new int*[m];</code> and then <code>matrix[i] = new int[n];</code> for every row. How many allocations with <code>new</code> are needed, and how many <code>delete[]</code> statements to free it?
$m+1$ and $1$
$m+1$ and $m+1$
$m$ and $m$
$m\cdot n$ and $m\cdot n$
Explanation. One <code>new</code> for the array of row pointers and one for each of the $m$ rows; each row is freed with <code>delete[] matrix[i]</code> and then the pointer array with <code>delete[] matrix</code>.
In C++, what does the program print? <pre>void f(int a[], int n) {
a[0] = 99;
}
int main() {
int b[3] = {1, 2, 3};
f(b, 3);
cout << b[0];
}</pre>
$1$
$0$
Compilation error
$99$
Explanation. An array passed to a function is not copied: the function receives the address of the first element, so it modifies <code>b</code> itself. An <code>int</code> passed by value, instead, would be a copy.
In C++ execution starts from the function <code>int main()</code>, which usually ends with <code>return 0;</code>. What does that value indicate?
To the terminal, that <code>main</code> printed nothing
To the compiler, that there are no errors
To the operating system, that the program ended well
To the operating system, to rerun the program
Explanation. The value returned by <code>main</code> is the exit code of the program: by convention $0$ means success, a different value signals an error.
FindMaximum in pseudocode sets $max:=a[1]$ and scans «for $i:=2$ to $n$». A C++ translation, with the array <code>a</code> of $n$ elements, writes <code>max = a[0];</code> and <code>for (int i = 1; i <= n; i++)</code>. What is the error?
It reads <code>a[n]</code>, outside the array (indices $0$ to $n-1$)
None: it is the exact translation of the loop
It skips the last element <code>a[n-1]</code>
It compares the first element twice
Explanation. In C++ indices go from $0$ to $n-1$: the right loop is <code>i < n</code>. With <code>i <= n</code> the last iteration reads a cell that does not belong to the array (C++ does not check it).
A C++ function for the maximum of an array initialises <code>int max = 0;</code> and then, for <code>i</code> from <code>0</code> to <code>n-1</code>, sets <code>max = a[i]</code> if <code>a[i] > max</code>. What does it return on <code>{-5, -2, -9}</code>?
$-2$
$-9$
$-5$
$0$
Explanation. No element exceeds $0$, so <code>max</code> stays $0$. This is why FindMaximum starts from $max:=a[1]$ (in C++ <code>a[0]</code>), an element of the array.
In C++ <code>|</code> is bitwise OR. For which pair of naturals $(a,b)$ does <code>(a | b) == a + b</code> hold?
$a=6$, $b=3$
$a=5$, $b=5$
$a=8$, $b=5$
$a=12$, $b=10$
Explanation. OR equals the sum when the two numbers have no $1$ bits in the same position (no carry): $1000\,|\,0101=1101=13=8+5$. For $6|3=7\ne 9$ the common bit $0010$ is counted only once.
A C++ program must compute $2^3$ and contains <code>cout << (2 ^ 3);</code>. What does it print?
$8$
$6$
$1$
$5$
Explanation. In C++ <code>^</code> is not exponentiation but bitwise XOR: $10\ \mathrm{XOR}\ 11=01=1$. For $2^3$ one uses <code>1 << 3</code> or <code>pow(2, 3)</code>.
In C++ <code>~</code> flips all bits. The type <code>unsigned char</code> has $8$ bits and holds the naturals $0$ to $255$. With <code>unsigned char a = 200;</code>, what is <code>(unsigned char)~a</code>?
$55$
$-200$
$56$
$255$
Explanation. Flipping the $8$ bits of $x$ gives $255-x=55$. $56=256-200$ would be the two's complement, that is the flip plus $1$.
In C++ an <code>int</code> is represented in two's complement and <code>~</code> flips all its bits. What does <code>int x = 5; cout << ~x;</code> print?
$-5$
$-6$
$2$
$250$
Explanation. In two's complement $-x$ is obtained by flipping the bits and adding $1$, so $\sim x=-x-1=-6$. $2=010$ flips only the $3$ bits of $101$; $250$ is the unsigned $8$-bit result.
In C++ <code>x << k</code> shifts the bits of <code>x</code> left by $k$ positions, adding zeros on the right. What is <code>3 << 4</code>?
$12$
$7$
$81$
$48$
Explanation. Shifting left by $k$ positions multiplies by $2^k$: $3\cdot 16=48$ ($11\to 110000$). $12=3\cdot 4$ and $81=3^4$ mistake $k$ for the factor.
In C++ (<code><<</code> left shift, <code>^</code> bitwise XOR), which expression equals $2^{10}=1024$?
<code>2 ^ 10</code>
<code>10 << 1</code>
<code>1 << 10</code>
<code>2 << 10</code>
Explanation. <code>1 << k</code> is a $1$ followed by $k$ zeros, that is $2^k$. <code>2 << 10</code> is $2^{11}=2048$, <code>10 << 1</code> is $20$, <code>2 ^ 10</code> is the XOR, $8$.
In C++, for an integer $x\ge 0$, <code>x >> k</code> shifts the bits right by $k$ positions (bits falling off are lost). What is <code>100 >> 3</code>?
$12$
$13$
$800$
$97$
Explanation. Shifting right by $k$ positions gives $\lfloor x/2^k\rfloor=\lfloor 100/8\rfloor=12$: the fractional part is lost, not rounded to $13$. $800$ is the left shift.
In C++ (<code>>></code> and <code><<</code> right and left shifts, evaluated left to right), what does <code>int x = 45; cout << (x >> 2) << " " << (x >> 2 << 2);</code> print?
<code>11 45</code>
<code>180 45</code>
<code>11 44</code>
<code>11 11</code>
Explanation. $45=101101$: <code>>> 2</code> gives $1011=11$ and loses the two least significant bits ($01$). Shifting it back left gives $101100=44$: the lost bits do not return, so the result is $45$ rounded down to a multiple of $4$.
In C++ the mask <code>1 << k</code> has only the bit in position $k$ set (positions start at $0$ on the right). What does <code>cout << (13 & (1 << 2));</code> print?
$4$
$1$
$0$
$13$
Explanation. $13=1101$ and the mask is $0100$: bit $2$ of $13$ is $1$, and the AND returns the value of the mask, $4$ (not $1$). In an if, a non-zero value counts as true.
In C++, with <code>int n = 15;</code> (bit positions start at $0$ on the right), what is <code>n</code> after <code>n = n & ~(1 << 2);</code>?
$4$
$15$
$7$
$11$
Explanation. <code>~(1 << 2)</code> has all bits $1$ except the one in position $2$: the AND clears that bit, $1111\to 1011=11$. $7$ clears bit $3$; $4$ is the value of the removed bit.
The C++ function <code>int sum(int a[], int n)</code> adds up <code>a[0]</code>, …, <code>a[n-1]</code> and assumes that the array has at least <code>n</code> elements. What happens if it is called with <code>n</code> larger than the actual size of the array?
The compiler reports the error
The program stops with an exception
It adds up only the existing elements
It reads cells outside the array, with no check
Explanation. C++ does not check indices: the cells past the end hold arbitrary values (undefined behaviour). Java would throw an exception, Python an <code>IndexError</code>.
A C++ function computes $n!$ in a $32$-bit <code>int</code> variable, whose maximum is $2^{31}-1=2147483647$ ($12!=479001600$, $13!=6227020800$). For which $n$ is the result correct?
For every $n$
For $n\le 12$
For $n\le 31$
For $n\le 20$
Explanation. $13!$ exceeds the maximum of an <code>int</code>: the result overflows and is no longer $13!$. The algorithm's correctness assumes the values fit in the type; $20$ is the limit of a $64$-bit <code>long long</code>.
In C++, the loop <code>int i = 0; while (i != n) i += 3;</code> stops only when <code>i</code> equals <code>n</code> exactly. For which integers <code>n</code> does it terminate?
For every $n\ge 0$
For every multiple $n$ of $3$, negative too
For $n\ge 0$ a multiple of $3$
Only for $n=0$
Explanation. <code>i</code> takes $0,3,6,\dots$: it meets <code>n</code> only if it is a non-negative multiple of $3$, otherwise it jumps over it. With <code>i < n</code> the loop would terminate for every <code>n</code>.
In C++, for $x\ge 0$, <code>x >> 1</code> equals $\lfloor x/2\rfloor$, like <code>x / 2</code> between integers. With <code>int x = -7;</code> (two's complement, sign-preserving shift), what do <code>x >> 1</code> and <code>x / 2</code> give?
$-4$ and $-3$
$-3$ and $-3$
$-4$ and $-4$
$3$ and $-3$
Explanation. <code>x >> 1</code> rounds towards $-\infty$: $\lfloor -3.5\rfloor=-4$; C++ integer division truncates towards zero: $-3$. The equivalence holds only under the hypothesis $x\ge 0$.
In Python, what are <code>-7 // 2</code> and <code>-7 % 2</code>?
$-3$ and $-1$
$-4$ and $-1$
$-4$ and $1$
$-3.5$ and $1$
Explanation. <code>//</code> computes $\lfloor a/b\rfloor$, rounding down: $\lfloor -3.5\rfloor=-4$, and the remainder is $-7-2\cdot(-4)=1$. $-3$ and $-1$ are the results of C++ and Java, which truncate toward zero.
In Python, which values does <code>i</code> take in <code>for i in range(2, 11, 3):</code>?
$2,5,8$
$2,5,8,11$
$3,6,9$
$2,4,6,8,10$
Explanation. <code>range(start, stop, step)</code> starts at <code>start</code> (included) and stops before <code>stop</code> (excluded), with increment <code>step</code>: $2,5,8$ ($11$ is excluded).
In Python, what happens when writing <code>x++</code> and <code>++x</code>?
Both increment <code>x</code> by $1$, exactly as happens in C++.
<code>x++</code> increments <code>x</code> after its use; <code>++x</code> is a syntax error.
<code>x++</code> is a syntax error; <code>++x</code> is accepted but does not increment <code>x</code>: its value is <code>x</code> itself.
Both are syntax errors: Python accepts neither of them.
Explanation. Python has no operators <code>++</code> and <code>--</code>: one writes <code>x += 1</code>. <code>++x</code> applies the unary plus twice and leaves the value unchanged.
Which statement about the Python language is correct?
It is interpreted, it uses dynamic typing, and the indentation of the blocks is mandatory.
It is compiled into an executable, like C++, and the blocks are delimited by curly braces.
Every variable must be declared with its data type before use.
Indentation is optional: it only improves readability.
Explanation. In Python the blocks (loops, conditional statements, functions) are defined by the indentation level, introduced by «:»; the data type of a variable is determined during the execution from the assigned value.
In Python, with <code>a = [4, 7, 1, 9]</code>, what is <code>a[1] + a[3]</code>?
$5$
$8$
An index error is raised
$16$
Explanation. The elements of a list are indexed from $0$: <code>a[1]</code> is $7$ and <code>a[3]</code> is $9$. With the pseudo-code indices starting at $1$ one would read $4+1=5$.
In Python 3, what does <code>print(6 / 3, 7 // 2)</code> print?
<code>2 3</code>
<code>2.0 3</code>
<code>2 3.5</code>
<code>2.0 3.5</code>
Explanation. In Python 3 the operator <code>/</code> always returns a <code>float</code>, even between two integers; the integer division is obtained with <code>//</code>. This is the opposite convention with respect to C++.
In Python blocks are defined by indentation. What does the program print? <pre>x = 5
if x > 10:
print("a")
print("b")</pre>
<code>b</code>
<code>a</code> and then <code>b</code>
Nothing
A syntax error, because the curly braces are missing
Explanation. Only <code>print("a")</code> is indented, so only it belongs to the block of the <code>if</code>, which is not executed ($5>10$ is false); <code>print("b")</code> is outside the block and is always executed.
In Python one executes <code>x = 5</code> and then <code>x = "five"</code>. What happens?
Error: <code>x</code> was created as an <code>int</code> and cannot receive a string.
The name <code>x</code> now refers to a string: typing is dynamic and there is no error.
<code>x</code> stays equal to $5$: the second assignment is ignored without messages.
<code>x</code> is <code>"five"</code>, but its data type stays <code>int</code>, the initial one.
Explanation. In Python variables are created by assignment and have no declared data type: after the second assignment <code>type(x)</code> is <code>str</code>.
In Python 3, what does <code>print(2 ** 100)</code> print (<code>**</code> is exponentiation)?
A negative number, because of integer overflow
The approximate value <code>1.2676506002282294e+30</code>
An error, because the result exceeds $2^{63}-1$
The exact integer $2^{100}$, with $31$ digits
Explanation. The integers of Python have no maximum value: <code>2 ** 100</code> is the exact integer <code>1267650600228229401496703205376</code>. In C++ and in Java the same value does not fit in an <code>int</code>.
In Python <code>sep</code> is the separator between the values of <code>print</code> (by default a space) and <code>end</code> the text written at the end (by default a new line). What appears on the screen? <pre>print("a", "b", "c", sep="-", end="!")
print("d")</pre>
<code>a b c!d</code> on a single line
<code>a-b-c!d</code> on a single line
<code>a-b-c-!d</code> on a single line
<code>a-b-c!</code> and then <code>d</code> on the next line
Explanation. The separator <code>-</code> goes only between the values; instead of the new line <code>!</code> is written, so the second <code>print</code> continues on the same line.
In Python one executes <code>n = input("n? ")</code>, the user types <code>7</code> and presses enter, and then <code>print(n * 2)</code>. What is printed?
<code>14</code>
A type error
<code>7 7</code>
<code>77</code>
Explanation. <code>input()</code> always returns a string: <code>"7" * 2</code> repeats the string and gives <code>77</code>. To obtain $14$ the conversion <code>int(input(…))</code> is needed.
In Python, what does the program print? <pre>x = 15
if x > 20:
print("A")
elif x > 10:
print("B")
elif x > 5:
print("C")
else:
print("D")</pre>
<code>B</code>
<code>B</code> and then <code>C</code>
<code>C</code>
<code>D</code>
Explanation. The conditions are evaluated in order and only the first branch with a true condition is executed: $15>20$ is false, $15>10$ is true, so <code>B</code> is printed and the other branches are skipped.
In Python the conditional expression <code>x if c else y</code> evaluates to <code>x</code> if <code>c</code> is true, otherwise to <code>y</code>. With <code>n = 5</code>, what is <code>"big" if n > 10 else "medium" if n > 5 else "small"</code>?
<code>"medium"</code>
<code>"big"</code>
<code>"small"</code>
A syntax error
Explanation. $5>10$ is false, so <code>"medium" if n > 5 else "small"</code> is evaluated; $5>5$ is also false, and the value is <code>"small"</code>.
In Python, with <code>a = [5, 7, 9]</code>, what is <code>s</code> at the end? <pre>s = 0
for i in range(len(a)):
s += i</pre>
$3$
$21$
$6$
$24$
Explanation. <code>range(len(a))</code> gives the indices $0,1,2$, and the loop adds the indices, not the elements: $s=0+1+2=3$. To add the elements one needs <code>s += a[i]</code> (or <code>for x in a</code>).
In Python, what does the program print? <pre>m = [[0] * 2] * 3
m[0][0] = 1
print(m)</pre>
<code>[[1, 0], [0, 0], [0, 0]]</code>
<code>[[1, 1], [0, 0], [0, 0]]</code>
<code>[[1, 0], [1, 0], [1, 0]]</code>
An index error
Explanation. <code>[[0] * 2] * 3</code> creates a list with three references to the same row: modifying one modifies all of them. Three distinct rows are obtained with <code>[[0] * 2 for _ in range(3)]</code>.
In Python, what does the program print? <pre>def f(a, x):
a[0] = 0
x = 0
b = [4, 7]
k = 5
f(b, k)
print(b, k)</pre>
<code>[4, 7] 5</code>
<code>[0, 7] 0</code>
<code>[4, 7] 0</code>
<code>[0, 7] 5</code>
Explanation. The parameter receives the same object as the argument: modifying an element of the list (<code>a[0] = 0</code>) is visible to the caller, while assigning a new value to <code>x</code> changes only the local name.
In Python, with <code>def divide(n, m): return n // m, n % m</code>, what does <code>print(divide(17, 5))</code> print?
<code>3 2</code>
<code>(3, 2)</code>
<code>[3, 2]</code>
<code>3</code>
Explanation. Several comma-separated values after <code>return</code> form a tuple, printed between round brackets. With <code>q, r = divide(17, 5)</code> the tuple is unpacked into two variables.
FindMaximum in pseudo-code executes «for $i:=2$ to $n$» on the array $a[1..n]$. In the Python translation <code>array_max_value(a)</code> the list <code>a</code> has indices from $0$ and $n$ is not a parameter. Which loop visits the same elements?
<code>for i in range(2, len(a) + 1):</code>
<code>for i in range(1, len(a)):</code>
<code>for i in range(1, len(a) + 1):</code>
<code>for i in range(2, len(a)):</code>
Explanation. The element $a[i]$ of the pseudo-code is <code>a[i-1]</code> in Python: the values $2,\dots,n$ become $1,\dots,n-1$, i.e., <code>range(1, len(a))</code> (the right end is excluded). <code>len(a)</code> replaces the parameter $n$.
The Python function <code>array_max_value(a)</code> sets <code>max_val = a[0]</code> and then scans <code>a[1]</code>, …, updating the maximum. Like FindMaximum, it assumes $n\ge 1$. What happens when it is called on an empty list <code>[]</code>?
The function returns $0$, the default initial value of an empty list.
The function returns <code>None</code>, because the loop executes no iteration.
The function returns $-\infty$, the maximum of the empty set.
The program stops with <code>IndexError</code>: the access to <code>a[0]</code> fails.
Explanation. The precondition $n\ge 1$ does not hold: <code>a[0]</code> does not exist and Python signals the access outside the list with <code>IndexError</code> (in C++ the same access would not be checked).
In Python integers have no fixed number of bits. What is <code>~12</code> (bitwise NOT)?
$3$
$-13$
$243$
$-12$
Explanation. In Python <code>~x</code> is always $-x-1$, so <code>~12</code> $=-13$. $3$ is the NOT on $4$ bits and $243$ the one on $8$ bits, obtained with the mask <code>~12 & 0xFF</code>.
In Python <code>>></code> and <code><<</code> are the right and left shifts, <code>^</code> the bitwise XOR. What does <code>print(20 >> 3, 5 << 2, 12 ^ 10)</code> print?
<code>2.5 20 6</code>
<code>2 10 6</code>
<code>2 20 14</code>
<code>2 20 6</code>
Explanation. <code>20 >> 3</code> $=\lfloor 20/2^3\rfloor=2$; <code>5 << 2</code> $=5\cdot 2^2=20$; <code>12 ^ 10</code>: $(1100)_2$ XOR $(1010)_2=(0110)_2=6$. $14$ is the OR, not the XOR.
Comparing C++ and Python, which pair of writings has the same meaning in the two languages?
<code>for (int i = 0; i < n; i++)</code> in C++ and <code>for i in range(n):</code> in Python
<code>c ? x : y</code> in C++ and <code>c ? x : y</code> in Python
<code>x++</code> in C++ and <code>x++</code> in Python
<code>pow(x, y)</code> in C++ and <code>x ^ y</code> in Python
Explanation. Both loops visit $0,1,\dots,n-1$. In Python the ternary operator is written <code>x if c else y</code>, the increment <code>x += 1</code>, and the power <code>x ** y</code> (<code>^</code> is the XOR).
Which values does the expression <code>10 / 3</code> give in C++ (between two <code>int</code>) and in Python 3?
$3.33333$ in C++ and $3.3333333333333335$ in Python
$3$ in both languages
$3$ in C++ and $3.3333333333333335$ in Python
$3.3333333333333335$ in C++ and $3$ in Python
Explanation. In C++ <code>/</code> between two integers is the integer division; in Python <code>/</code> always gives a <code>float</code>, and the integer division is written <code>//</code>.
In Python, with <code>a = [1, 2, 3]</code> and then <code>b = a</code>, one runs <code>b.append(4)</code>. Which statement is correct?
<code>b</code> is a copy, and <code>a</code> stays <code>[1, 2, 3]</code>
<code>b = a</code> raises an error
<code>a</code> is also <code>[1, 2, 3, 4]</code>
<code>append</code> creates a new list
Explanation. Assignment binds a new name to the same object; a copy needs <code>b = a.copy()</code> or <code>b = a[:]</code>. It is the same reason why <code>[[0]*2]*3</code> repeats the same row.
In Python the logical operators are <code>and</code>, <code>or</code>, <code>not</code>. Which statement is correct?
They are written as words, and <code>and</code> and <code>or</code> evaluate the second operand only if needed
They are written <code>&&</code>, <code>||</code>, <code>!</code> as in C++
<code>and</code> always evaluates both operands
<code>not</code> is a bitwise operator
Explanation. Python uses the words <code>and</code>, <code>or</code>, <code>not</code>, with short-circuit evaluation; <code>&</code>, <code>|</code>, <code>~</code> are the bitwise operators.
The Python program is saved in the file <code>sum.py</code>. How is it run?
First with <code>g++ sum.py</code>, then by launching the executable
With <code>python3 sum.py</code>: the interpreter runs it line by line
First with <code>javac sum.py</code>, then with <code>java sum</code>
By typing <code>main()</code> on the first line of the terminal
Explanation. Python is interpreted: there is no separate compilation into an executable, and no mandatory <code>main</code> function. <code>g++</code> and <code>javac</code> are the C++ and Java compilers.
In Python <code>int(s)</code> converts a string to an integer and <code>+</code> between two strings concatenates them. What does <code>print(int("12") + 3, "12" + "3")</code> print?
<code>15 15</code>
<code>15 123</code>
<code>123 123</code>
A type error
Explanation. <code>int("12")</code> is the integer $12$, so $12+3=15$; <code>"12" + "3"</code> concatenates two strings. The error would come with <code>"12" + 3</code>, which mixes a string and an integer.
In Python, inside the braces of an f-string the format <code>:.kf</code> shows a real number with $k$ digits after the point, rounding. What does <code>print(f"{2 / 3:.2f}")</code> print?
<code>0.67</code>
<code>0.66</code>
<code>0.6666666666666666</code>
<code>{2 / 3:.2f}</code>
Explanation. $2/3=0.666\ldots$ rounded to two digits gives $0.67$ (it is not truncated to $0.66$). Without the <code>f</code> before the quotes the text would be printed as it is.
In Python, with <code>a, b = 3, 4</code>, what does <code>print(f"{a}+{b}={a+b}")</code> print?
<code>{a}+{b}={a+b}</code>
<code>3+4=34</code>
<code>3+4=7</code>
<code>a+b=7</code>
Explanation. In an f-string each expression in braces is evaluated and replaced by its value: <code>{a+b}</code> is $7$, while the text outside the braces stays as it is.
In Python <code>//=</code> assigns floor division, <code>**=</code> the power, <code>%=</code> the remainder. What is <code>x</code> after <code>x = 10</code>, <code>x //= 3</code>, <code>x **= 2</code>, <code>x %= 5</code>?
$9$
$4$
$4.0$
$1$
Explanation. $10//3=3$, $3^2=9$, $9\bmod 5=4$. With <code>/=</code> instead of <code>//=</code> the result would be a float.
In Python, in the multiple assignment <code>a, b = e1, e2</code> both expressions are evaluated first and then assigned. What does the program print? <pre>a, b = 1, 2
a, b = b, a + b
print(a, b)</pre>
<code>2 4</code>
<code>1 3</code>
<code>2 2</code>
<code>2 3</code>
Explanation. On the right $b=2$ and $a+b=3$ are computed with the old values, then $a=2$, $b=3$. $2\ 4$ is what two assignments in sequence (<code>a = b</code>, then <code>b = a + b</code>) would give.
In Python the C++ increment <code>++</code> and decrement <code>--</code> operators do not exist. What does the program print? <pre>x = 4
y = --x
print(x, y)</pre>
<code>3 3</code>
<code>4 4</code>
<code>4 3</code>
A syntax error
Explanation. <code>--x</code> is read as $-(-x)$, two sign changes: its value is $4$ and <code>x</code> is not modified. To decrement one writes <code>x -= 1</code>.
In Python comparisons can be chained: <code>0 < x <= 10</code> means <code>0 < x and x <= 10</code>. With <code>x = 7</code>, what does <code>print(0 < x <= 5, 1 < 3 > 2)</code> print?
<code>True True</code>
<code>False False</code>
A syntax error
<code>False True</code>
Explanation. $0<7$ is true but $7\le 5$ is false, hence <code>False</code>; <code>1 < 3 > 2</code> is <code>1 < 3 and 3 > 2</code>, true. In C++ the same expression would compare a boolean with a number.
In Python, what does <code>print(3 == 3.0, "3" == 3)</code> print?
<code>True False</code>
<code>False False</code>
<code>True True</code>
A type error
Explanation. <code>==</code> compares values: the integer $3$ and the real $3.0$ are equal. A string is never equal to a number, but the comparison is legal and gives <code>False</code> (the error comes with <code><</code>, not with <code>==</code>).
In Python <code>not</code> has lower precedence than comparisons and higher than <code>and</code> and <code>or</code>. With <code>x = 5</code>, what does <code>print(not x > 3 or x == 5)</code> print?
<code>False</code>
<code>1</code>
<code>True</code>
A syntax error
Explanation. It reads <code>(not (x > 3)) or (x == 5)</code>: <code>not True</code> is <code>False</code>, and <code>False or True</code> is <code>True</code>. Python prints booleans as <code>True</code> and <code>False</code>.
In Python, what does the program print? <pre>n = 12
if n % 2 == 0:
print("even")
if n % 3 == 0:
print("three")
else:
print("other")</pre>
<code>even</code> and then <code>three</code>
Only <code>even</code>
<code>even</code>, <code>three</code> and <code>other</code>
<code>even</code> and then <code>other</code>
Explanation. They are two separate if statements, not a chain with elif: both are checked. The else branch belongs to the second if, and it does not run because $12$ is a multiple of $3$.
In Python the conditional expression <code>x if c else y</code> is <code>x</code> if <code>c</code> is true, otherwise <code>y</code>. With <code>a, b = 3, 8</code>, what does the program print? <pre>m = a if a > b else b
s = "even" if m % 2 == 0 else "odd"
print(m, s)</pre>
<code>3 odd</code>
<code>8 odd</code>
<code>8 even</code>
<code>3 even</code>
Explanation. $a>b$ is false, so $m=b=8$, the larger of the two; $8\bmod 2=0$ gives <code>even</code>.
In Python, what does the program print? <pre>i = 10
while i > 0:
i -= 3
print(i)</pre>
$1$
$0$
$-3$
$-2$
Explanation. $i$ takes $10,7,4,1$ and then $-2$: the condition is checked before every iteration, and $1>0$ causes one last subtraction. The print is outside the loop (it is not indented).
In Python <code>for x in a</code> assigns to <code>x</code>, one after the other, the elements of the list <code>a</code>. What is <code>s</code> at the end? <pre>a = [3, 8, 1]
s = 0
for x in a:
s += x * x</pre>
$74$
$12$
$5$
$144$
Explanation. <code>x</code> takes the values (not the indices) $3,8,1$: $9+64+1=74$. $5=0+1+4$ would be the result using the indices $0,1,2$; $144=12^2$ squares the sum.
In Python, what does the program print? (<code>end=" "</code> writes a space instead of a newline) <pre>for i in range(1, 10):
if i % 4 == 0:
break
print(i, end=" ")</pre>
<code>1 2 3 4</code>
<code>1 2 3 5 6 7 9</code>
<code>1 2 3</code>
<code>4</code>
Explanation. At $i=4$ <code>break</code> leaves the loop before printing. Skipping only the multiples of $4$ would be the effect of <code>continue</code>.
In Python, what is <code>s</code> at the end? <pre>s = 0
for i in range(10):
if i % 3 != 0:
continue
s += i</pre>
$18$
$27$
$45$
$0$
Explanation. <code>continue</code> skips the rest of the iteration when $i$ is not a multiple of $3$: one adds $0,3,6,9$. <code>range(10)</code> goes from $0$ to $9$; $27$ is the sum of the non-multiples of $3$.
In Python a two-dimensional list is a list of rows. With <code>m = [[1, 2, 3], [4, 5, 6]]</code>, what does <code>print(len(m), len(m[0]), m[1][2])</code> print?
<code>3 2 6</code>
<code>2 3 5</code>
<code>2 3 6</code>
<code>6 3 6</code>
Explanation. <code>len(m)</code> counts the rows ($2$), <code>len(m[0])</code> the elements of the first row ($3$); <code>m[1][2]</code> is the row with index $1$ and the column with index $2$, counting from $0$.
In Python, what does the program print? <pre>def double(x):
y = 2 * x
print(double(3))</pre>
<code>6</code>
<code>None</code>
<code>0</code>
An error
Explanation. A function that ends without <code>return</code> returns the special value <code>None</code>: <code>y</code> is computed but not returned.
In Python, what happens when running the program? <pre>def g():
t = 10
return t + 1
r = g()
print(r, t)</pre>
It prints <code>11 10</code>, both values
It prints <code>11 11</code>
It prints <code>11 None</code>
Error: <code>t</code> is not defined
Explanation. <code>t</code> is a local variable of <code>g</code>: outside the function the name is not defined (<code>NameError</code>). The result leaves the function only through <code>return</code>.
The Python function for the maximum sets <code>max_val = a[0]</code> and then runs <code>for i in range(1, n):</code>, where <code>n = len(a)</code>. Which indices does the loop visit?
$1,2,\dots,n$
$1,2,\dots,n-1$
$2,3,\dots,n$
$0,1,\dots,n-1$
Explanation. <code>range(1, n)</code> starts at $1$ and stops before $n$; with the list indices, $0$ to $n-1$, these are all but the first, already used to initialise <code>max_val</code>.
FindMaximum requires an array with $n\ge 1$ elements. Its Python translation sets <code>max_val = a[0]</code> and then scans <code>a[1:]</code>. What happens calling it with the empty list <code>[]</code>?
It returns $0$
It returns <code>None</code>
It returns $-\infty$
<code>IndexError</code> on <code>a[0]</code>
Explanation. The empty list has no element with index $0$, so the initialisation fails. This is the precondition $n\ge 1$ on the input: without elements the maximum does not exist.
In Python integers have no fixed number of bits and <code><<</code> is the left shift. What does <code>print(1 << 70)</code> print?
$0$, because the bits fall off on the left
An overflow error (<code>OverflowError</code>)
$1180591620717411303424$, that is $2^{70}$
$140$, that is $70\cdot 2$
Explanation. <code>1 << k</code> is $2^k$, and in Python an integer grows as needed. In C++ a $32$-bit <code>int</code> could not hold it; $140=70\cdot 2$ mistakes the shift for multiplication by $2$.
Comparing C++ and Python, which statement about blocks and variables is correct?
C++ and Python: blocks in braces; the type is declared only in C++
C++: indented blocks; Python: blocks in braces, type declared
C++ and Python: indented blocks, type always declared
C++: blocks in braces, type declared; Python: indented blocks, no type declared
Explanation. C++: <code>{ … }</code> and <code>int x = 5;</code>. Python: colon and indentation, and <code>x = 5</code> binds the name to an object, whose type belongs to the object.
The pseudocode of the notes indexes arrays from $1$ to $n$. How are a C++ array and a Python list of $n$ elements indexed?
Both from $1$ to $n$
Both from $0$ to $n-1$
From $0$ to $n-1$ in C++, from $1$ to $n$ in Python
From $1$ to $n$ in C++, from $0$ to $n-1$ in Python
Explanation. C++ and Python start at $0$: translating pseudocode, $a[i]$ becomes <code>a[i-1]</code>, and «for $i:=1$ to $n$» becomes a loop over the indices $0$ to $n-1$.
The Python function <code>def mean(a): return sum(a) / len(a)</code> computes the mean of a list. Which hypothesis on the input is needed, and what happens without it?
<code>a</code> sorted; otherwise the result is wrong
Explanation. With <code>a = []</code> one computes <code>0 / 0</code>, and Python raises <code>ZeroDivisionError</code>. <code>/</code> accepts integers and reals, and order does not matter for the sum.
In Java, what does <code>System.out.println(Integer.MAX_VALUE + 1);</code> print?
$2147483648$
$-2147483648$
An error message
$0$
Explanation. An <code>int</code> has $32$ bits in two's complement, with interval $[-2^{31},2^{31}-1]$: the result does not fit and «wraps around» to the other end, with no error message. With <code>(long)</code> one would get $2147483648$.
In Java, with <code>int n = 42;</code>, what does <code>System.out.println("n + 1 = " + n + 1);</code> print?
<code>n + 1 = 421</code>
<code>n + 1 = 43</code>
<code>n + 1 = 42 1</code>
A compilation error
Explanation. The operator <code>+</code> is evaluated from the left: string plus <code>n</code> gives the string <code>"n + 1 = 42"</code>, to which <code>1</code> is concatenated. For the sum parentheses are needed, <code>(n + 1)</code>.
In Java, what are <code>-7 / 2</code> and <code>-7 % 2</code>?
$-4$ and $1$
$-3.5$ and $-1$
$-3$ and $-1$
$-4$ and $-1$
Explanation. As in C++, the division between integers truncates the quotient toward zero: $-3$, with remainder $-7-2\cdot(-3)=-1$. $-4$ and $1$ are the results of <code>//</code> and <code>%</code> in Python.
It uses dynamic typing: the data type of a variable depends on the last value assigned.
It is strongly and statically typed: every variable is declared with its data type, which cannot change during the execution.
The entry point of a program is the first instruction of the file, outside any class.
The blocks are defined by indentation, as in Python.
Explanation. In Java every program is organized into classes and starts from the <code>main</code> method of a class; blocks are between curly braces and every instruction ends with «;».
In Java an <code>int</code> has $32$ bits and a <code>long</code> $64$. What does the fragment print? <pre>int big = Integer.MAX_VALUE; // 2147483647
long b = (long) big + 1;
System.out.println(b);</pre>
$2147483648$
$-2147483648$
$2147483647$
A compilation error
Explanation. The conversion <code>(long)</code> happens before the addition, which is therefore computed with $64$ bits: $2^{31}-1+1=2^{31}$. Without the conversion, <code>big + 1</code> would overflow to $-2147483648$.
In Java, on a computer with English settings (decimal separator: point), what does <code>System.out.printf("%d / %d = %.2f%n", 10, 4, 10.0 / 4);</code> print? (<code>%d</code>: integer, <code>%.2f</code>: two decimal digits, <code>%n</code>: new line.)
<code>10 / 4 = 2.5</code>
<code>10 / 4 = 2</code>
<code>10 / 4 = 2.50</code>
<code>%d / %d = 2.50</code>
Explanation. The placeholders are replaced in order by the arguments: <code>%d</code> by $10$ and $4$, <code>%.2f</code> by $2.5$ written with exactly two decimal digits. The division <code>10.0 / 4</code> is not an integer division, because <code>10.0</code> is a <code>double</code>.
In Java, with <code>int n = 15;</code>, one writes <code>if (n % 2) { … }</code>. What happens?
The block is executed because $n$ is odd, as would happen in C++.
The block is not executed, because <code>n % 2</code> is $1$ and not <code>true</code>.
The program compiles, but it stops with an exception during the execution.
Compilation error: in Java the condition must be of data type <code>boolean</code>.
Explanation. In Java an integer is not converted into a Boolean value: the correct condition is <code>(n % 2) == 1</code>. In C++ a non-zero value would count as true.
In Java <code>c ? x : y</code> evaluates to <code>x</code> if <code>c</code> is true, otherwise to <code>y</code>. What does the fragment print? <pre>int a = 7, b = 3;
String r = (a % b == 0) ? "divisible" : "remainder " + a % b;
System.out.println(r);</pre>
<code>divisible</code>
<code>remainder 1</code>
<code>remainder 2</code>
<code>remainder 0</code>
Explanation. $7\bmod 3=1\ne 0$: the third operand is evaluated, the string <code>"remainder "</code> concatenated with the value of <code>a % b</code>, i.e., $1$.
In Java the division <code>/</code> between two <code>int</code> values is an integer division. What is <code>c</code> at the end? <pre>int i = 10, c = 0;
while (i > 1) {
i = i / 2;
c++;
}</pre>
$3$
$4$
$5$
$2$
Explanation. $i$ goes from $10$ to $5$, to $2$ and to $1$: three iterations, then the condition $1>1$ is false. With non-integer division ($5$, $2.5$, $1.25$, $0.625$) there would be $4$ iterations.
In Java, what happens when executing <code>int[] a = {9, 12, 3}; System.out.println(a[3]);</code>?
The program stops with the exception <code>ArrayIndexOutOfBoundsException</code>
$3$, the last element of the array, is printed
$0$, the default value of an <code>int</code>, is printed
An unpredictable value is printed, as in C++
Explanation. The indices go from $0$ to <code>a.length - 1</code> $=2$. Java checks every access and signals index $3$ with an exception; in C++ the same access is not checked.
In Java <code>add(x)</code> appends <code>x</code> at the end of an <code>ArrayList</code> and <code>set(i, x)</code> replaces the element of index <code>i</code> (indices from $0$). What does the fragment print? <pre>ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= 4; i++) list.add(i * i);
list.set(1, 50);
System.out.println(list);</pre>
<code>[50, 4, 9, 16]</code>
<code>[1, 50, 4, 9, 16]</code>
<code>[1, 50, 9, 16]</code>
<code>[1, 4, 50, 16]</code>
Explanation. After the loop the list is $[1,4,9,16]$; <code>set(1, 50)</code> replaces (does not insert) the element of index $1$, i.e., the second one.
In a Java class the method <code>static int addition(int a, int b)</code> is written after <code>main</code> and called inside <code>main</code>. What happens?
Compilation error: as in C++, the method must be written before <code>main</code>.
It works: in Java the order of the methods inside a class does not matter.
It works only if the method is declared <code>public</code> instead of <code>static</code>.
The program compiles, but it stops with an error when it reaches the call.
Explanation. Unlike C++, a Java method can be called before the point where it is defined in the class. A method called from <code>main</code> without an object must be <code>static</code>.
Explanation. The entry point is the method <code>main</code> of a class, with this header; <code>int main()</code> is the one of C++ and <code>def</code> defines functions in Python.
FindMaximum in pseudo-code scans $a[2..n]$ with «for $i:=2$ to $n$». In Java the array <code>int[] a</code> has indices from $0$ and knows its own size. Which loop visits the same elements?
<code>for (int i = 1; i <= a.length; i++)</code>
<code>for (int i = 1; i < a.length; i++)</code>
<code>for (int i = 1; i < a.length(); i++)</code>
<code>for (int i = 2; i < a.length; i++)</code>
Explanation. The second element has index $1$ and the last one <code>a.length - 1</code>. <code>length</code> is a field of the array, not a method: <code>a.length()</code> does not compile; with <code><=</code> the loop would go outside the array.
The Java method computing the maximum sets <code>max = a[0]</code> and, for <code>i</code> from <code>1</code> to <code>a.length - 1</code>, compares <code>a[i] > max</code>. On <code>{9, 12, 3, 16, 19, 11, 12}</code>, how many times does it evaluate the comparison <code>a[i] > max</code>?
$7$
$3$
$5$
$6$
Explanation. The comparison is made once for each <code>i</code> from $1$ to $6$, i.e., $n-1=6$ times, whatever the array; $3$ is the number of true comparisons (the updates of the maximum).
In Java an <code>int</code> has $32$ bits in two's complement; <code>>></code> shifts to the right keeping the sign, <code>>>></code> always adds zeros on the left. What are <code>-8 >> 1</code> and <code>-8 >>> 28</code>?
$-4$ and $-1$
$4$ and $15$
$-4$ and $15$
$-4$ and $0$
Explanation. $-8=(11\dots11000)_2$: <code>>> 1</code> copies the sign bit and gives $-4$; <code>>>> 28</code> keeps only the $4$ most significant bits, $(1111)_2=15$. With <code>>> 28</code> one would get $-1$.
In Java (<code>|</code>: OR, <code>&</code>: AND, <code>~</code>: bitwise NOT, <code><<</code>: left shift), what is <code>x</code> at the end? <pre>int x = 6;
x = x | (1 << 3);
x = x & ~(1 << 1);</pre>
$12$
$14$
$4$
$10$
Explanation. $6=(0110)_2$; the OR with <code>1 << 3</code> $=(1000)_2$ sets bit $3$ to $1$: $(1110)_2=14$; the AND with the NOT of $(0010)_2$ clears bit $1$: $(1100)_2=12$.
A function must produce two results. According to the comparison among the three languages of the course, how is it usually done in C++, in Java and in Python?
C++: returning a tuple; Java: parameters passed by reference; Python: returning an array
In all three: parameters passed by reference, written with the symbol <code>&</code>
C++: returning an array; Java: returning a tuple; Python: parameters passed by reference
C++: parameters passed by reference; Java: returning an array; Python: returning a tuple
Explanation. In C++ the results are written into <code>int&</code> parameters; Java passes parameters by value and returns the results together in an array; Python returns a tuple, unpacked with a multiple assignment.
What happens, in C++, in Java and in Python, when accessing an index outside the range of an array (or of a list)?
In all three languages the program stops with an exception that indicates the wrong index.
In C++ the access is not checked; in Java and in Python the program stops with an exception.
In C++ and in Java the access is not checked; in Python the program stops with an exception.
In all three languages the value $0$ is read, without errors or messages.
Explanation. Java (<code>ArrayIndexOutOfBoundsException</code>) and Python (<code>IndexError</code>) check the indices; C++ does not, and the access reads or writes an unpredictable memory area.
In Java every variable has a declared type, and primitive types have fixed size. Which statement is correct?
An <code>int</code> has unlimited precision
The size of an <code>int</code> depends on the processor
An <code>int</code> always has $32$ bits, and can overflow
A variable may change type
Explanation. Java fixes the size of primitive types independently of the machine: <code>Integer.MAX_VALUE + 1</code> gives <code>Integer.MIN_VALUE</code>. Larger integers need <code>long</code> or <code>BigInteger</code>.
In Java a method receives a parameter of primitive type (for instance <code>int</code>) and modifies it inside. Which statement is correct?
The change is always seen by the caller
The change is not seen by the caller (pass by value)
In Java primitive parameters are passed by reference, like <code>int&</code> in C++
A method cannot modify its parameters
Explanation. Java always passes by value; for reference types the copied value is the reference, so a method can change the elements of an array but cannot make the caller's variable point to another array.
In Java an array is created with a size, for instance <code>int[] a = new int[5];</code>. Which statement is correct?
The size grows automatically if one writes past the end
Indices go from $1$ to $5$
Uninitialized elements have random values, as in C++
The size is fixed at creation, indices go from $0$ to <code>a.length - 1</code>, and the elements start at $0$
Explanation. A Java array has fixed length and indices from $0$; an out-of-bounds access throws an exception. For a growing list one uses <code>ArrayList</code>; Java initializes <code>int</code>s to $0$.
A Java source file contains the class <code>public class Hello</code> with the <code>main</code> method. What must the file be called?
<code>hello.java</code>
<code>Hello.class</code>
<code>main.java</code>
<code>Hello.java</code>
Explanation. The file name is the name of the public class, with the same capitalisation, and extension <code>.java</code>. <code>Hello.class</code> is the bytecode file produced by <code>javac</code>.
A Java program uses <code>Scanner</code> to read from the keyboard. What must be written at the start of the file, before the class?
<code>#include <Scanner></code>
<code>import java.util.Scanner;</code>
<code>using namespace java;</code>
Nothing: <code>Scanner</code> is always available
Explanation. Library classes outside <code>java.lang</code> are imported with <code>import</code>. <code>#include</code> and <code>using namespace</code> belong to C++.
In Java a <code>char</code> is a numeric code (the character <code>'a'</code> has code $97$), and in an expression with an <code>int</code> it becomes an integer. What does <code>System.out.println('a' + 1);</code> print?
<code>b</code>
<code>a1</code>
$98$
Compilation error
Explanation. <code>'a' + 1</code> is a sum of integers, $97+1=98$. One would get <code>b</code> with <code>(char)('a' + 1)</code>, and <code>a1</code> with the string <code>"a" + 1</code>.
In Java <code>System.out.print</code> prints without a newline, <code>System.out.println</code> adds a newline after printing. What appears on the screen? <pre>System.out.print("a");
System.out.println("b");
System.out.print("c");</pre>
<code>ab</code> on one line and <code>c</code> on the next
<code>abc</code> on a single line
<code>a</code>, <code>b</code> and <code>c</code> on three lines
<code>a</code> on one line and <code>bc</code> on the next
Explanation. After <code>a</code> there is no newline; <code>println("b")</code> writes <code>b</code> and then a newline, so <code>c</code> starts a new line.
In Java, with <code>Scanner sc = new Scanner(System.in);</code>, which statement reads an integer typed by the user?
<code>int n = sc.nextLine();</code>
<code>int n = input();</code>
<code>int n = sc.nextInt();</code>
<code>int n = cin >> n;</code>
Explanation. <code>nextInt()</code> reads the next integer; <code>nextLine()</code> returns a <code>String</code>, which cannot be assigned to an <code>int</code>. <code>input()</code> is Python, <code>cin</code> is C++.
In Java division <code>/</code> between two <code>int</code>s is integer division and <code>%</code> is the remainder. What does <code>System.out.println(7 / 2 * 2 + 7 % 2);</code> print?
$7$
$8$
$6$
$7.0$
Explanation. $7/2=3$ (integer), $3\cdot 2=6$, $7\%2=1$: $6+1=7$. It always holds that $(a/b)\cdot b+a\%b=a$. $8$ would use $3.5\cdot 2$.
In Java, with <code>int x = 10;</code>, the statements <code>x += 2.7;</code> and <code>x = x + 2.7;</code> are compared. Which statement is correct?
Both compile, and <code>x</code> becomes $12.7$
Only <code>x += 2.7;</code> compiles, giving $12$
Neither of the two statements compiles
Both compile, and <code>x</code> becomes $13$
Explanation. <code>x + 2.7</code> is a <code>double</code>, which Java does not assign to an <code>int</code> without an explicit cast. The compound operator instead includes the cast: <code>x = (int)(x + 2.7)</code>, that is $12$ (truncation).
In Java, what does the fragment print? <pre>double d = 10;
d /= 4;
int i = 10;
i /= 4;
System.out.println(d + " " + i);</pre>
<code>2.5 2.5</code>
<code>2 2</code>
<code>2.0 2</code>
<code>2.5 2</code>
Explanation. <code>d /= 4</code> divides a <code>double</code>: $2.5$. <code>i /= 4</code> divides two integers: $\lfloor 10/4\rfloor=2$. The type of the variable decides the kind of division.
In Java operands are evaluated from left to right; <code>i--</code> returns the value and then decrements, <code>--i</code> decrements and then returns. After <code>int i = 5; int j = i-- - --i;</code>, what are <code>j</code> and <code>i</code>?
$j=0$, $i=3$
$j=1$, $i=4$
$j=2$, $i=3$
$j=2$, $i=4$
Explanation. <code>i--</code> is $5$ and brings <code>i</code> to $4$; then <code>--i</code> brings <code>i</code> to $3$ and is $3$. So $j=5-3=2$ and $i=3$.
In Java, what does the fragment print? <pre>String s = new String("ciao");
String t = new String("ciao");
System.out.println((s == t) + " " + s.equals(t));</pre>
<code>false true</code>
<code>true true</code>
<code>true false</code>
<code>false false</code>
Explanation. Between objects <code>==</code> compares references: <code>s</code> and <code>t</code> are two distinct objects. <code>equals</code> compares the content, which is equal. Strings are compared with <code>equals</code>.
In Java <code>double</code>s follow the IEEE 754 standard in base $2$. What does <code>System.out.println(0.1 + 0.2 == 0.3);</code> print?
<code>true</code>
Compilation error
<code>false</code>
$0$
Explanation. $0.1$, $0.2$ and $0.3$ are not exactly representable in base $2$: the sum is about $0.30000000000000004$, different from the value stored for $0.3$. Reals are compared through $|a-b|$ with a small tolerance.
In Java, between two <code>boolean</code>s, <code>&&</code> evaluates the second operand only if needed, while <code>&</code> always evaluates both. What does the fragment print? <pre>int i = 0, j = 0;
if (false && (++i > 0)) { }
if (false & (++j > 0)) { }
System.out.println(i + " " + j);</pre>
<code>1 1</code>
<code>0 0</code>
<code>1 0</code>
<code>0 1</code>
Explanation. With <code>&&</code> the false first operand is enough to decide, so <code>++i</code> is not executed. With <code>&</code> <code>++j</code> runs too, although the result is false anyway.
In Java, what does the fragment print with <code>int x = -5;</code>? <pre>if (x > 0)
if (x > 10)
System.out.println("A");
else
System.out.println("B");</pre>
<code>B</code>
Nothing
<code>A</code>
<code>A</code> and then <code>B</code>
Explanation. An else binds to the nearest if that does not have one yet, that is to <code>if (x > 10)</code>, whatever the indentation. Since $x>0$ is false, nothing runs. Braces select the intended if.
In Java the ternary operator <code>c ? x : y</code> is <code>x</code> if <code>c</code> is true, otherwise <code>y</code>. What does the fragment print? <pre>int a = 4, b = 9;
int m = (a > b) ? a : b;
String s = (m % 2 == 0) ? "even" : "odd";
System.out.println(m + " " + s);</pre>
<code>4 even</code>
<code>9 even</code>
<code>4 odd</code>
<code>9 odd</code>
Explanation. $a>b$ is false, so $m=b=9$, the larger of the two; $9\%2=1$ gives <code>odd</code>.
In Java, what is <code>count</code> at the end? <pre>int count = 0;
for (int i = 1; i <= 3; i++)
for (int j = 1; j <= 3; j++) {
if (j == 2) break;
count++;
}</pre>
$1$
$9$
$3$
$6$
Explanation. <code>break</code> leaves only the innermost loop: for each $i$ only $j=1$ is counted, then at $j=2$ control returns to the outer loop. $1$ would assume that <code>break</code> leaves both loops.
In Java, what is <code>s</code> at the end? <pre>int s = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
s += i;
}</pre>
$25$
$30$
$55$
$1$
Explanation. <code>continue</code> skips the rest of the iteration for even values: one adds the odd ones $1+3+5+7+9=25$. $30$ is the sum of the even ones, $1$ what <code>break</code> would give.
In Java, after <code>int[][] m = new int[3][4];</code>, what does <code>System.out.println(m.length + " " + m[0].length);</code> print?
<code>4 3</code>
<code>12 12</code>
<code>3 4</code>
<code>2 3</code>
Explanation. A two-dimensional array is an array of rows: <code>m.length</code> is the number of rows ($3$), <code>m[0].length</code> the number of elements in a row ($4$). $2\ 3$ are the last valid indices.
In Java, what does <code>int[][] m = new int[2][3]; System.out.println(m[1][2]);</code> print, with no other assignments?
$0$
<code>null</code>
An unpredictable value
Compilation error: <code>m</code> is not initialised
Explanation. In Java the elements of an array created with <code>new</code> start from the default value of the type: $0$ for <code>int</code>. In C++ an uninitialised local array would instead hold unpredictable values.
In Java <code>add(x)</code> appends <code>x</code> to an <code>ArrayList</code>, <code>add(i, x)</code> inserts it at position <code>i</code> shifting the following ones right, <code>get(i)</code> reads the element with index <code>i</code> (from $0$). What does the fragment print? <pre>ArrayList<Integer> l = new ArrayList<>();
l.add(5);
l.add(8);
l.add(0, 3);
System.out.println(l.get(1) + " " + l.size());</pre>
<code>8 3</code>
<code>3 3</code>
<code>5 3</code>
<code>5 2</code>
Explanation. After the two <code>add</code>s the list is $[5,8]$; <code>add(0, 3)</code> inserts at the front: $[3,5,8]$. The element with index $1$ is $5$ and there are $3$ elements (<code>add(i, x)</code> does not replace, unlike <code>set</code>).
In Java an array parameter receives a copy of the reference to the array. What does the program print? <pre>static int f(int[] a) {
a[0] = 7;
a = new int[]{1};
return a[0];
}
// in main:
int[] b = {4, 5};
int r = f(b);
System.out.println(b[0] + " " + r);</pre>
<code>4 1</code>
<code>7 1</code>
<code>1 1</code>
<code>7 7</code>
Explanation. <code>a[0] = 7</code> modifies the array of <code>b</code>. Then <code>a = new int[]{1}</code> makes only the local copy point to a new array: <code>b</code> no longer changes, and the function returns $1$.
The Java method <code>static int arrayMaxValue(int[] a)</code> receives only the array, without the number of elements $n$. How does it get $n$?
With <code>a.length()</code>
With <code>a.size()</code>
With <code>len(a)</code>
With <code>a.length</code>
Explanation. A Java array knows its own length: <code>length</code> is a field, without parentheses. <code>length()</code> is the <code>String</code> method, <code>size()</code> the <code>ArrayList</code> one, <code>len</code> the Python function.
A Java method for the maximum sets <code>int max = Integer.MIN_VALUE;</code> (the smallest <code>int</code>) and then, for every <code>i</code> from <code>0</code> to <code>a.length - 1</code>, updates <code>max</code> if <code>a[i] > max</code>. Is it correct?
No: with only negative numbers it returns <code>Integer.MIN_VALUE</code>
Yes, provided the array has at least one element
No: <code>Integer.MIN_VALUE</code> is not an <code>int</code> value
Yes, even on the empty array, for which it returns $0$
Explanation. Every <code>int</code> is $\ge$ <code>Integer.MIN_VALUE</code>, so after the loop <code>max</code> is the maximum (even if all equal <code>MIN_VALUE</code>). With zero elements the loop does not run and the result is not an element: the precondition $n\ge 1$ is needed.
In Java <code>&</code>, <code>|</code> and <code>^</code> are bitwise AND, OR and XOR. What does <code>System.out.println((5 & 3) + " " + (5 | 3) + " " + (5 ^ 3));</code> print?
<code>1 7 8</code>
<code>0 7 6</code>
<code>1 8 6</code>
<code>1 7 6</code>
Explanation. $5=101$, $3=011$: AND $001=1$, OR $111=7$, XOR $110=6$. $8=5+3$ mistakes OR (or XOR) for the sum.
In Java an <code>int</code> always has $32$ bits in two's complement. What does <code>System.out.println(1 << 31);</code> print?
$2147483648$
$0$
$-2147483648$
Compilation error
Explanation. <code>1 << 31</code> sets the most significant bit, whose weight in two's complement is $-2^{31}$: it is <code>Integer.MIN_VALUE</code>. $2^{31}$ is not representable in an <code>int</code>, whose maximum is $2^{31}-1$.
An array whose size $n$ is known only at run time is created in C++ with <code>new int[n]</code>, in Java with <code>new int[n]</code>, in Python with <code>[0] * n</code>. Who frees the memory when the array is no longer needed?
In C++ the programmer (<code>delete[]</code>), elsewhere the system
In all three the programmer, with <code>delete[]</code>
In all three the system, automatically
In Java the programmer (<code>delete[]</code>), elsewhere the system
Explanation. C++ has no automatic memory collector: what is allocated with <code>new</code> is freed with <code>delete[]</code>. Java and Python free unreachable memory by themselves.
How are programs written in the three languages of the course executed?
All three compiled to machine code before they are executed
C++ compiled to machine code; Java compiled to bytecode for the JVM; Python interpreted
C++ interpreted; Java and Python compiled to machine code
C++ and Java interpreted line by line; Python compiled to bytecode for the JVM
Explanation. <code>g++</code> produces an executable for the machine; <code>javac</code> produces <code>.class</code> files run by the Java Virtual Machine; the <code>python3</code> interpreter runs the source directly.
In Java ($32$-bit <code>int</code>), BinarySearch computes the middle index as <code>left + (right - left) / 2</code> instead of <code>(left + right) / 2</code>. For indices $0\le left\le right$, when does the second formula give a wrong result?
Never: the two formulas are always equal
When <code>left + right</code> exceeds <code>Integer.MAX_VALUE</code>
When <code>left</code> and <code>right</code> are odd
When <code>right - left</code> is negative
Explanation. Mathematically they coincide, but the sum of two large indices overflows and becomes negative. <code>right - left</code> never exceeds <code>right</code>, so the first formula is safe.
In Java, <code>int n = sc.nextInt();</code> (with <code>Scanner sc</code> on the keyboard) assumes that the next item typed is an integer. What happens if the user types <code>abc</code>?
<code>n</code> gets $0$, the default value
<code>n</code> gets the code of the character <code>a</code>
The program does not compile at all
Reading fails with an exception
Explanation. The item cannot be converted to <code>int</code>, so reading fails at run time. The compiler cannot know what the user will type.
Which condition defines $f(n)=\Theta\big(g(n)\big)$?
For all $c_1,c_2\in\R_{>0}$ there exists $n_1\in\N$ such that $0\le c_1\,g(n)\le f(n)\le c_2\,g(n)$ for all $n\ge n_1$.
There exist $c_1,c_2\in\R_{>0}$ and $n_1\in\N$ such that $0\le c_1\,g(n)\le f(n)\le c_2\,g(n)$ for all $n\ge n_1$.
There exist $c\in\R_{>0}$ and $n_1\in\N$ such that $0\le f(n)\le c\,g(n)$ for all $n\ge n_1$.
$0\le g(n)\le f(n)\le 2\,g(n)$ for all $n\ge 1$.
Explanation. This is Definition 9.2: two positive constants and a common threshold. The condition with a single constant, $0\le f(n)\le c\,g(n)$, defines $\bigO$; with «for all $c_1,c_2$» the condition holds for no pair of positive functions.
There exist $c\in\R_{>0}$ and $n_1\in\N$ such that $0\le f(n)<c\,g(n)$ for all $n\ge n_1$.
For all $c\in\R_{>0}$ there exists $n_1\in\N$ such that $0\le c\,g(n)<f(n)$ for all $n\ge n_1$.
$f(n)<g(n)$ for all $n\in\N$.
For all $c\in\R_{>0}$ there exists $n_1\in\N$ such that $0\le f(n)<c\,g(n)$ for all $n\ge n_1$.
Explanation. This is Definition 9.9: the inequality must hold for every positive constant, however small. With «there exists $c$» one gets (essentially) the definition of $\bigO$; with $c\,g(n)<f(n)$ one has the definition of $\omega$.
To prove with the definition that $f(n)=3n^2+5n=\Theta(n^2)$, which choice of constants works?
$c_1=3$, $c_2=4$, $n_1=5$
$c_1=3$, $c_2=3$, $n_1=1$
$c_1=4$, $c_2=8$, $n_1=1$
$c_1=1$, $c_2=4$, $n_1=1$
Explanation. $3n^2\le 3n^2+5n$ always holds, and $3n^2+5n\le 4n^2$ is equivalent to $5n\le n^2$, i.e., $n\ge 5$. With $c_2=3$ the upper bound never holds, with $c_1=4$ the lower one holds only for $n\le 5$, with $n_1=1$ and $c_2=4$ the upper one fails for $n<5$.
Explanation. The definition of $o$ holds for every $c>0$, in particular for $c=1$, which is the definition of $\bigO$ (Observation 9.12). The converse implications are false: $n=\bigO(n)$ but $n\ne o(n)$.
Explanation. The sum of asymptotically non-negative functions is $\Theta$ of the maximum (Observation 9.7), and the lower-order terms can be dropped (Observation 9.20): $n^2$ remains.
Let $0\le c_1\,g(n)\le f(n)\le c_2\,g(n)$ for all $n\ge n_1$. With which constants do we prove that $f(n)+g(n)=\Theta\big(g(n)\big)$?
$c_1$ and $c_2$, with the same threshold $n_1$
$2c_1$ and $2c_2$, with threshold $2n_1$
$c_1-1$ and $c_2+1$, with the same threshold $n_1$
$c_1+1$ and $c_2+1$, with the same threshold $n_1$
Explanation. Adding $g(n)\ge 0$ to the three members: $(c_1+1)\,g(n)\le f(n)+g(n)\le(c_2+1)\,g(n)$ for $n\ge n_1$ (Observation 9.6). With $c_1-1$ the constant might not be positive.
Let $f$, $g$ be asymptotically positive and let $L=\lim_{n\to+\infty} f(n)/g(n)$ exist ($0^+$, $\ell\in\R_{>0}$ or $+\infty$). Which statement of the limit criterion is correct?
$f(n)=\bigO\big(g(n)\big)$ if and only if $L\in\R_{>0}$.
$f(n)=\bigO\big(g(n)\big)$ if and only if $L=0^+$ or $L\in\R_{>0}$.
$f(n)=\Omega\big(g(n)\big)$ if and only if $L=+\infty$.
$f(n)=\Theta\big(g(n)\big)$ if and only if $L=1$.
Explanation. Proposition 9.18: $\bigO$ corresponds to a finite $L$ ($0^+$ or positive), $\Omega$ to a positive or infinite $L$, $\Theta$ to any $L\in\R_{>0}$ (for instance $3n^2=\Theta(n^2)$ with $L=3$).
$f(n)=\Theta\big(g(n)\big)$ and $g(n)=\bigO\big(h(n)\big)\ \Longrightarrow\ f(n)=\Theta\big(h(n)\big)$
Explanation. This is transpose symmetry (Proposition 9.19). Symmetry holds only for $\Theta$: $n=\bigO(n^2)$ but $n^2\ne\bigO(n)$. The «mixed» transitivity with $\Theta$ and $\bigO$ is also false: $n=\Theta(n)$ and $n=\bigO(n^2)$, but $n\ne\Theta(n^2)$.
Let $f$, $g$ be asymptotically positive and $L=\lim_{n\to+\infty}f(n)/g(n)$. Which results are needed to prove that $L=\ell\in\R_{>0}$ or $L=0^+$ implies $f(n)=\bigO\big(g(n)\big)$?
Limit $+\infty\Leftrightarrow\omega$, and $\omega\Rightarrow\Omega$; then transpose symmetry.
The definition of $\Theta$ and the fact that $f+g=\Theta(\max\{f,g\})$.
Limit in $\R_{>0}$ $\Rightarrow\Theta\Rightarrow\bigO$; limit $0^+\Leftrightarrow o$, and $o\Rightarrow\bigO$.
The transitivity of $o$ and the symmetry of $\Theta$, applied to $f/g$.
Explanation. The two cases are handled separately: $\ell>0$ gives $\Theta$ and hence $\bigO$; $0^+$ gives $o$ and hence $\bigO$. The results on $+\infty$ and $\omega$ are needed for the criterion of $\Omega$.
Observation 9.11 states that $\lim_{n\to+\infty} f(n)/g(n)=0^+$ if and only if $f(n)=o\big(g(n)\big)$. Which assumption on $f$ and $g$ does it require?
That $f$ and $g$ are asymptotically positive, so that one can multiply and divide by $g(n)>0$.
That $f$ and $g$ are asymptotically increasing, so that the ratio has a limit.
That $g$ is bounded, so that the ratio $f(n)/g(n)$ does not diverge.
That $f(n)\le g(n)$ for all $n\in\N$, not only from a threshold on.
Explanation. The proof goes from $0\le f(n)/g(n)<\varepsilon$ to $0\le f(n)<\varepsilon\,g(n)$ by multiplying by $g(n)$, and back: $g(n)>0$ (and $f(n)>0$ for the limit $0^+$) is needed from some $n$ on.
We have $f(n)=\omega\big(g(n)\big)$ if for every $c\in\R_{>0}$ there exists $n_1\in\N$ such that $0\le c\,g(n)<f(n)$ for all $n\ge n_1$. With $f(n)=n^2/4$, $g(n)=n$ and $c=10$, what is the smallest threshold $n_1$ that satisfies the condition?
$40$
$10$
$4$
$41$
Explanation. $10\,n<n^2/4$ is equivalent to $n>40$ (for $n\ge 1$), so the smallest threshold is $n_1=41$; with $n=40$ equality holds, which is not enough because the inequality is strict. For every $c$ a threshold exists ($n_1=4c+1$): $f=\omega(g)$.
Let $f(n)=\bigO(n\log_2 n)$ and $g(n)=\Theta(n^2)$; moreover, $n\log_2 n=\bigO(n^2)$. Which conclusion follows from the relational properties (transitivity, symmetry, transpose symmetry)?
$f(n)=\Theta\big(g(n)\big)$
$f(n)=\bigO\big(g(n)\big)$
$g(n)=\bigO\big(f(n)\big)$
$f(n)=\Omega\big(g(n)\big)$
Explanation. By transitivity $f=\bigO(n^2)$; by symmetry $n^2=\Theta(g)$, hence $n^2=\bigO(g)$, and again by transitivity $f=\bigO(g)$. An upper bound says nothing about a lower bound: $f$ might even be constant.
Let $f$ and $g$ be asymptotically non-negative functions of a natural variable, with $g(n)=\bigO\big(f(n)\big)$. Which statement is correct?
$f(n)+g(n)=\Theta\big(g(n)\big)$
$f(n)+g(n)=o\big(f(n)\big)$
$f(n)+g(n)=\Theta\big(f(n)\big)$
$f(n)+g(n)=\Theta\big(f(n)\,g(n)\big)$
Explanation. From $0\le g(n)\le c\,f(n)$ eventually it follows that $1\cdot f(n)\le f(n)+g(n)\le(1+c)\,f(n)$: lower-order terms can be dropped. This is why $3n^2+5n$ is $\Theta(n^2)$.
About an algorithm we only know that its worst-case number of steps, on inputs of size $n$, is $S(n)=\bigO(n^2)$. What can be concluded?
For $n$ large enough it performs at most $c\,n^2$ steps on every input of size $n$; it might also perform far fewer.
For $n$ large enough it performs at least $c\,n^2$ steps on some input of size $n$, for a constant $c>0$.
It performs exactly $c\,n^2$ steps on every input of size $n$, for a constant $c>0$ that depends on the algorithm.
It performs $\Theta(n^2)$ steps on every input of size $n$, because $\bigO$ describes the worst case.
Explanation. $\bigO$ is an upper bound: it does not exclude, for instance, $S(n)=\Theta(n)$. A lower bound requires $\Omega$, and the exact order $\Theta$.
One writes $f(n)=O(g(n))$ if there are $c>0$ and $n_1 \in \N$ with $0 \le f(n) \le c\,g(n)$ for every $n \ge n_1$. Which statement is correct?
$3n^2+5n=O(n)$, since $c$ can be chosen large
$f(n)=O(g(n))$ implies $f(n) \le g(n)$ for every $n$
$O(n^2)$ means «exactly quadratic»
$3n^2+5n=O(n^2)$ and also $3n^2+5n=O(n^3)$
Explanation. $O$ is an upper bound: with $c=8$ and $n_1=1$ we have $3n^2+5n \le 8n^2 \le 8n^3$. No constant keeps $n^2$ below $c\,n$ forever; the inequality holds only from $n_1$ on and with the factor $c$.
One writes $f(n)=\Omega(g(n))$ if there are $c>0$ and $n_1$ with $0 \le c\,g(n) \le f(n)$ for every $n \ge n_1$. Which statement is true?
$n^2/10=\Omega(n)$
$n=\Omega(n^2)$
$\log_2 n=\Omega(n)$
$5=\Omega(n)$
Explanation. $\Omega$ is a lower bound: $n^2/10 \ge 1 \cdot n$ for $n \ge 10$. In the other options the function on the left grows more slowly than the one on the right.
Observation: $f(n)=\Theta(g(n))$ if and only if $f(n)=O(g(n))$ and $f(n)=\Omega(g(n))$. How are the constants of $\Theta$ ($c_1\,g(n) \le f(n) \le c_2\,g(n)$ for $n \ge n_1$) obtained from those of $O$ and $\Omega$?
$c_1=c_2$ always
$n_1$ equal to the minimum of the two $n_1$
$c_1$ from $\Omega$, $c_2$ from $O$, and $n_1$ equal to the maximum of the two $n_1$
They are not: limits of ratios are needed
Explanation. From $n_1=\max$ on both inequalities hold. With the minimum, one of the two might not hold yet; limits are only a sufficient criterion.
Let $f,g$ be asymptotically nonnegative. Which statement is correct?
$\max\{f(n),g(n)\}=\Theta(f(n)+g(n))$
$f(n)+g(n)=\Theta(f(n)\,g(n))$
$\max\{f(n),g(n)\}=o(f(n)+g(n))$
$f(n)+g(n)=\Theta(\min\{f(n),g(n)\})$
Explanation. $\max \le f+g \le 2\max$: the sum is at most twice the maximum. This is why, in an algorithm with phases, the most expensive phase counts.
For asymptotically positive functions, $\lim_{n \to \infty} f(n)/g(n)=+\infty$ if and only if $f(n)=\omega(g(n))$. With $f(n)=n\log_2 n$ and $g(n)=n$, what is concluded?
$n\log_2 n=\Theta(n)$
$n\log_2 n=o(n)$
$n\log_2 n=\omega(n)$
Nothing can be concluded
Explanation. $f(n)/g(n)=\log_2 n \to +\infty$, so $n\log_2 n$ grows strictly faster than $n$. $\Theta$ would need a finite positive limit.
Which implication between asymptotic notations is always true?
$f(n)=\Omega(g(n)) \Rightarrow f(n)=\omega(g(n))$
$f(n)=\omega(g(n)) \Rightarrow f(n)=\Theta(g(n))$
$f(n)=O(g(n)) \Rightarrow f(n)=o(g(n))$
$f(n)=\omega(g(n)) \Rightarrow f(n)=\Omega(g(n))$
Explanation. $\omega$ asks $f \ge c\,g$ eventually for every $c>0$, $\Omega$ for a single $c$: the first is stronger. The converse is false: $n=\Omega(n)$ but not $\omega(n)$.
Observation: if $\lim_{n \to \infty} f(n)/g(n)=\ell \in \R_{>0}$, then $f(n)=\Theta(g(n))$. Which choice of constants proves it, using the definition of limit?
$c_1=c_2=\ell$
$c_1=\ell/2$ and $c_2=2\ell$, for large $n$
$c_1=0$ and $c_2=\ell$
$c_1=1$ and $c_2=\ell+1$ for every $n \ge 1$
Explanation. With $\varepsilon=\ell/2$ the ratio is eventually in $[\ell/2,3\ell/2] \subseteq [\ell/2,2\ell]$. $c_1=0$ gives no lower bound; equality holds only in the limit.
Limit criterion for $\Omega$: if $\lim f(n)/g(n)$ is a positive number or $+\infty$, then $f(n)=\Omega(g(n))$. For which pair does the criterion give $f=\Omega(g)$?
$f(n)=n^2$, $g(n)=n^2+n$
$f(n)=n$, $g(n)=n^2$
$f(n)=\log_2 n$, $g(n)=n$
$f(n)=1$, $g(n)=n$
Explanation. $n^2/(n^2+n) \to 1>0$, so $n^2=\Omega(n^2+n)$ (indeed $\Theta$). In the other pairs the ratio tends to $0$.
In the graphical interpretation of $f(n)=\Theta(g(n))$, what is required of the values of $f$?
They must lie between $c_1\,g(n)$ and $c_2\,g(n)$ for every $n \ge 1$
From a threshold $n_1$ on they must lie between $c_1\,g(n)$ and $c_2\,g(n)$; before $n_1$ nothing
They must coincide with $g(n)$ from $n_1$ on
They must stay below $g(n)$ for every $n$
Explanation. Asymptotic notations describe the eventual behaviour: for $n<n_1$ the function may do anything. The constants $c_1,c_2$ allow a «band» around $g$.
In the graph illustrating $f(n)=O(g(n))$, the curve of $f$ lies below the curve $c\,g(n)$ from some $n_1$ on. What can be said about the curve $c\,g(n)$ with respect to $f$ for $n<n_1$?
It must lie above $f$ also for $n<n_1$
It must cross $f$ exactly at $n_1$
It must coincide with $f$
Nothing: for $n<n_1$ the curve of $f$ may lie above $c\,g(n)$
Explanation. The definition asks $f(n) \le c\,g(n)$ only for $n \ge n_1$. In the graph $n_1$ is often the crossing point, but any larger threshold works.
$f(n)=\Theta(g(n))$ if there are $c_1,c_2>0$ and $n_1$ with $c_1\,g(n)\le f(n)\le c_2\,g(n)$ for every $n\ge n_1$. Which function is NOT $\Theta(n^2)$?
$n^2/100+n$
$5n^2-3n$
$(n+1)^2$
$n^2\log_2 n$
Explanation. $n^2\log_2 n/n^2=\log_2 n$ is unbounded, so no constant $c_2$ works. The other three, divided by $n^2$, tend to a positive constant ($1/100$, $5$, $1$).
$f(n)=o(g(n))$ if for every $c>0$ there is $n_1$ with $0\le f(n)<c\,g(n)$ for every $n\ge n_1$; $\omega$ is the symmetric relation. Which statement is true?
$2n=o(n)$
$n\log_2 n=o(n^2)$
$n^2=o(n^2+n)$
$n^2=\omega(n^2-n)$
Explanation. $n\log_2 n/n^2=\log_2 n/n\to 0$. Instead $2n<c\,n$ fails for $c\le 2$, and $n^2/(n^2+n)\to 1$: functions of the same order are never $o$ of each other.
We have $3n=\bigO(n)$ (there are $c>0$ and $n_1$ with $3n\le c\,n$ for $n\ge n_1$). Why instead is $3n\ne o(n)$, where $o$ requires $3n<c\,n$ eventually for EVERY $c>0$?
Because $o$ requires $f$ to be decreasing
Because $3n$ is not asymptotically non-negative
Because $o$ is used only for logarithmic functions
Because for $c\le 3$ the inequality $3n<c\,n$ fails for every $n\ge 1$
Explanation. In $\bigO$ one constant suffices ($c=3$); in $o$ all are needed, even the smallest, and with $c=1$ one would need $3n<n$. $o(g)$ means «negligible with respect to $g$».
Asymptotic notations are transitive: from $f=\bigO(g)$ and $g=\bigO(h)$ it follows that $f=\bigO(h)$. Suppose instead that $f(n)=\bigO(g(n))$ and $h(n)=\bigO(g(n))$. What follows between $f$ and $h$?
Nothing, in general
That $f(n)=\bigO(h(n))$
That $f(n)=\Theta(h(n))$
That $h(n)=\bigO(f(n))$
Explanation. The two hypotheses give only upper bounds with the same $g$, and transitivity does not apply. With $g=n^2$: $f=n$, $h=n^2$ gives $h\ne\bigO(f)$; $f=n^2$, $h=n$ gives $f\ne\bigO(h)$.
Among the relational properties of asymptotic notations, which holds for $\Theta$ but NOT for $\bigO$?
Transitivity: $f=\Theta(g)$, $g=\Theta(h)$ give $f=\Theta(h)$
Reflexivity: $f=\Theta(f)$ for every $f$
Symmetry: $f=\Theta(g)$ if and only if $g=\Theta(f)$
Passing to multiples: $c\,f=\Theta(f)$ for $c>0$
Explanation. $n=\bigO(n^2)$ but $n^2\ne\bigO(n)$: $\bigO$ is not symmetric (instead $f=\bigO(g)\Leftrightarrow g=\Omega(f)$ holds). Transitivity and reflexivity hold for $\Theta$, $\bigO$ and $\Omega$.
Algorithm A performs $\Theta(n^2)$ steps and algorithm B $\Theta(n\log_2 n)$ steps on inputs of size $n$. Which statement is correct?
B is faster from some $n$ on, not necessarily before
B performs fewer steps than A for every value $n\ge 1$
A and B are equivalent, because both are polynomial
A performs fewer steps than B for every value $n\ge 1$
Explanation. Asymptotic notations hide constants and thresholds: for instance $n^2$ against $100\,n\log_2 n$ favours A while $n<100\log_2 n$. For large $n$ the smaller order of growth wins.
An algorithm performs, on inputs of size $n$, $\Theta(n^2)$ steps in the worst case and $\Theta(n)$ in the best case (like Insertion Sort). Which statement about its number of steps $T$ on an arbitrary input of size $n$ is correct?
$T=\Theta(n^2)$ on every input
$T=\Theta(n)$ on every input
$T=\bigO(n^2)$ and $T=\Omega(n)$
$T=\Theta(n^{1.5})$ on every input
Explanation. Every input takes at most as long as the worst case and at least as long as the best. One cannot say $\Theta(n^2)$ for all inputs: on a sorted array the steps are $\Theta(n)$.
In the definition of $f(n)=\bigO(g(n))$ one asks $0\le f(n)\le c\,g(n)$ only for every $n\ge n_1$. What would happen asking it for every $n\ge 1$?
Nothing: the two definitions are equivalent
Every function would be $\bigO$ of every other
$n=\bigO(n\log_2 n)$ would become false, because $\log_2 1=0$
One could choose $c=0$
Explanation. For $n=1$ one would need $1\le c\cdot 0$, false for every $c$. The threshold $n_1$ serves to ignore small values: only the behaviour for large $n$ counts.
The limit criterion requires $\lim_{n\to+\infty}f(n)/g(n)$ to exist. With $f(n)=n\,(2+(-1)^n)$ and $g(n)=n$ the ratio alternates between $1$ and $3$. What can be concluded?
$f(n)=\Theta(n)$ by the definition ($c_1=1$, $c_2=3$)
$f$ and $g$ are not comparable
$f(n)=o(n)$, because the limit does not exist
$f(n)=\omega(n)$, because the ratio does not converge
Explanation. Without a limit the criterion does not apply, but the definition does: $n\le f(n)\le 3n$ for every $n$. The criterion is a sufficient condition, not a necessary one.
For asymptotically non-negative functions $\max\{f(n),g(n)\}=\Theta(f(n)+g(n))$. What happens dropping the non-negativity hypothesis, for instance with $f(n)=n$ and $g(n)=-n$?
It still holds, with the same constants
It holds with $c_1=0$
It fails: $f+g=0$ while $\max\{f,g\}=n$
It fails because $\max\{f,g\}=-n$
Explanation. The proof uses $\max\{f,g\}\le f+g\le 2\max\{f,g\}$, which requires $f,g\ge 0$. With negative terms the sum can vanish.
A function $f(n)$ has a sub-linear order of growth if $f(n)=o(n)$. Which function has a sub-linear order of growth?
$n\log_2 n$
$\frac{n}{2}+5$
$n^{0.9}$
$n^{1.1}$
Explanation. Sub-linear means $f(n)=o(n)$: for $\alpha<1$ we have $n^\alpha=o(n)$ (Observation 10.19). $\frac n2+5=\Theta(n)$ is linear, $n\log_2 n$ and $n^{1.1}$ are super-linear.
Which relation holds between $\log_2(5n)$ and $\log_{10} n$?
$\log_2(5n)=\omega(\log_{10} n)$
$\log_2(5n)=\Theta(\log_{10} n)$
$\log_2(5n)=o(\log_{10} n)$
Neither is $\bigO$ of the other
Explanation. $\log_2(5n)=\log_2 5+\log_2 n$ and $\log_2 n=\log_{10}n/\log_{10}2$: the ratio tends to $1/\log_{10}2\in\R_{>0}$ (Observation 10.13). The base and constant factors in the argument do not matter.
Which statement about exponential functions is true?
$2^{2n}=\Theta(2^n)$
$2^{n/2}=\Theta(2^n)$
$3^n=\Theta(2^n)$
$2^{2n}=\omega(2^n)$
Explanation. $2^{2n}/2^n=2^n\to+\infty$: a constant factor in the exponent changes the order (Observation 10.22), as does a different base (10.21). Only a shift of the exponent leaves it unchanged: $2^{n+5}=\Theta(2^n)$.
What is the order of growth of the polynomial $4n^3-100n^2+7$?
$\Theta(n^2)$
$\Theta(n^3)$
$\bigO(n^3)$ but not $\Theta(n^3)$, because of the negative coefficient
$\Theta(n^5)$
Explanation. By Observation 10.20 a polynomial of degree $k$ with leading coefficient $a_k>0$ is $\Theta(n^k)$: the ratio with $n^3$ tends to $4$. Negative coefficients of the lower-degree terms do not matter.
Which relation holds between $n\log_2 n$ and $n^{1.01}$?
$n\log_2 n=\omega(n^{1.01})$
$n\log_2 n=\Theta(n^{1.01})$
It depends on the base of the logarithm
$n\log_2 n=o(n^{1.01})$
Explanation. $\frac{n\log_2 n}{n^{1.01}}=\frac{\log_2 n}{n^{0.01}}\to 0^+$ because every positive power grows faster than every logarithm (Observation 10.15). For small $n$, $n\log_2 n$ is larger, but only the asymptotic behaviour counts.
A function $f(n)$ is polynomially bounded if $f(n)=\bigO(n^\alpha)$ for some constant $\alpha>0$. Which function is not polynomially bounded?
$1.01^n$
$n^{100}$
$n^5\log_2 n$
$\sqrt n$
Explanation. Polynomially bounded means $f(n)=\bigO(n^\alpha)$ for some $\alpha>0$. For every $\alpha$ we have $n^\alpha=o(1.01^n)$, so $1.01^n$ is not (it is exponentially bounded); $n^5\log_2 n=\bigO(n^6)$.
Which statement on the comparison between powers of the logarithm $\log_a^\beta n$ and powers $n^\alpha$ is correct?
The limit $\lim_{n\to+\infty}\log_a^\beta n/n^\alpha$ is $0^+$ only if $\alpha\ge 1$.
The limit is $0^+$ only if $\alpha>\beta$.
For $\alpha=\beta$ the limit is $1$.
For every $\alpha\in\R_{>0}$, $\beta\in\R_{>0}$ and $a\in\R_{>1}$ we have $\lim_{n\to+\infty}\log_a^\beta n/n^\alpha=0^+$.
Explanation. Every power of the logarithm, even with a large $\beta$, is $o$ of every positive power of $n$, even with a small $\alpha$: for instance $\log_2^{10} n=o(n^{0.1})$.
How do we prove that $\log_a^\beta n=o(n^\alpha)$ for all $\alpha,\beta>0$ and $a>1$ ($o$: $f=o(g)$ if $0\le f(n)<c\,g(n)$ eventually, for every $c>0$)?
With the change of base $\log_a n=\log_2 n/\log_2 a$, which reduces everything to $a=2$, without limits.
With the limit $\lim_{n\to+\infty}\log_a^\beta n/n^\alpha=0^+$ and the limit criterion ($L=0^+\Leftrightarrow o$).
With the limit $\lim_{n\to+\infty}n^\alpha/b^n=0^+$ between powers and exponentials, for $b>1$.
With the fact that $\log_a^\beta n$ and $n^\alpha$ are both asymptotically increasing.
Explanation. All the observations of the hierarchy have the same structure: a known limit of the hierarchy of infinities, then the limit criterion to translate it into the notation $o$.
A function $f$ of a natural variable is asymptotically increasing if there exists $n_1$ such that $f(n)<f(n+1)$ for all $n\ge n_1$. Which of the following functions is not asymptotically increasing?
$f(n)=n^2-10n$
$f(n)=\log_2 n$
$f(n)=\lfloor n/2\rfloor$
$f(n)=2^n/n$
Explanation. $\lfloor 2k/2\rfloor=\lfloor(2k+1)/2\rfloor=k$: the strict inequality fails for infinitely many $n$. $n^2-10n$ increases from $n=5$ on, and $2^{n+1}/(n+1)>2^n/n$ for $n>1$.
The families of increasing functions of a natural variable include the logarithms $\log_a n$, the powers $n^\alpha$ and the exponentials $b^n$. For which values of the parameters are these functions asymptotically increasing?
$a>1$, $\alpha>0$, $b>1$
$a>0$, $\alpha>0$, $b>0$
$a>1$, $\alpha\ge 1$, $b>1$
$a\ge 1$, $\alpha>0$, $b\ge 1$
Explanation. With $0<a<1$ the logarithm decreases and with $a=1$ it is not defined; $n^\alpha$ increases for every $\alpha>0$ (also $\sqrt n$); $b^n$ increases only for $b>1$, while $1^n$ is constant.
Which statement of the hierarchy of infinities (limits as $n\to+\infty$ of functions of a natural variable) is correct?
We have $\lim b^n/n!=0^+$ only for $1<b<e$; for $b\ge e$ the limit is $+\infty$.
For every $b\in\R_{>1}$ we have $\lim b^n/n!=0^+$.
We have $\lim n!/n^n=+\infty$, because $n!$ has $n$ factors like $n^n$.
For $\alpha>b>1$ we have $\lim n^\alpha/b^n=+\infty$.
Explanation. The ratio test gives $\frac{b^{n+1}/(n+1)!}{b^n/n!}=\frac{b}{n+1}\to 0$ for every base $b$. Moreover $n!/n^n\to 0^+$ and $n^\alpha/b^n\to 0^+$ for every $\alpha>0$, $b>1$.
For every constant $\alpha>0$ and $b>1$, which statement about the hierarchy of infinities is correct?
$\lim_{n \to \infty} n^{\alpha}/b^{n}=+\infty$ if $\alpha>b$
$n^{100}$ grows faster than $1.01^n$
$\lim_{n \to \infty} n^{\alpha}/b^{n}=0$: every exponential beats every power
The limit depends on the ratio between $\alpha$ and $b$
Explanation. Whatever the exponent $\alpha$ and whatever base $b>1$, the exponential wins: even $n^{100}=o(1.01^n)$, although the overtaking happens for very large $n$.
Proposition: $\lim_{n \to \infty} n!/n^n=0$. The proof uses the ratio test. Which fact closes the computation?
The ratio of consecutive terms is $(n/(n+1))^n \to 1/e<1$
$n! \le n$ for every $n$
$n^n$ is a polynomial
The ratio of consecutive terms tends to $1$
Explanation. $\frac{(n+1)!}{(n+1)^{n+1}}\cdot\frac{n^n}{n!}=\left(\frac{n}{n+1}\right)^n \to e^{-1}<1$, so the sequence tends to $0$. A ratio tending to $1$ would not allow a conclusion.
Limit criterion: let $L=\lim f(n)/g(n)$ for asymptotically positive functions, with $L=0$, $L \in \R_{>0}$ or $L=+\infty$. Which correspondence is correct?
$L=1 \Leftrightarrow f=O(g)$, and in the other cases nothing follows
Explanation. A ratio tending to $0$ says $f$ is negligible with respect to $g$, a diverging one that $g$ is negligible with respect to $f$, a finite positive limit that they have the same order.
Which relation between $10^n$ and $n!$ is correct?
$n!=o(10^n)$
$10^n=\Theta(n!)$
It depends on $n$: they cannot be compared asymptotically
$10^n=o(n!)$
Explanation. For every base $b>1$, $b^n=o(n!)$: from $n>2b$ on every new factor of $n!$ is much larger than $b$. For small $n$ $10^n$ is larger, but the behaviour at infinity counts.
For constants $a>1$ and $\lambda>0$, which statement about the logarithm is correct?
$\log_a(n+\lambda)=\omega(\log_a n)$
$\log_a(\lambda n)=o(\log_a n)$
$\log_a(n+\lambda)=\Theta(n)$
$\log_a(n+\lambda)=\Theta(\log_a n)$
Explanation. $\log_a(n+\lambda)/\log_a n \to 1$: shifting the argument does not change the order. Also $\log_a(\lambda n)=\log_a\lambda+\log_a n=\Theta(\log_a n)$.
An algorithm $A$ takes $\Theta(n\log_2 n)$ steps and an algorithm $B$ takes $\Theta(n)$. What can be said for large $n$?
They are equivalent, since $\log_2 n$ is almost constant
$A$ is faster, since $\log_2 n<n$
$B$ is asymptotically faster, since $n\log_2 n=\omega(n)$
They cannot be compared
Explanation. $n\log_2 n/n=\log_2 n \to \infty$: the quasi-linear function grows strictly faster than the linear one, though slowly. Hidden constants matter only for small $n$.
$(n+\lambda)^{\alpha} \le n^{\alpha}$ for every $n$
The binomial expansion holds only for integer $\alpha$, so the observation holds only for $\alpha \in \N$
Explanation. The limit criterion with limit $1$ gives $\Theta$, for every real $\alpha>0$. $(n+\lambda)^\alpha \ne n^\alpha+\lambda^\alpha$ in general.
Which relation is correct for $\lambda=5$ and $\alpha=3$?
$(5n)^3=\omega(n^3)$
$(5n)^3=\Theta(n^{15})$
$(5n)^3=\Theta(n^3)$
$(5n)^3=o(n^3)$
Explanation. $(5n)^3=125\,n^3$: a multiplicative constant does not change the order of growth. Scaling the argument of an exponential, instead, does change it.
What is the order of growth of the polynomial $f(n)=0.01\,n^4-100\,n^3+5000\,n$?
$\Theta(n^4)$
$\Theta(n^3)$
$\Theta(n)$
$O(1)$, since the leading coefficient is small
Explanation. A polynomial with positive leading coefficient has the order of its highest-degree term, whatever the other coefficients: $f(n)/n^4 \to 0.01>0$.
The functions $\log_2 n$, $\sqrt{n}$, $n$, $n\log_2 n$, $n^2$, $2^n$ are sorted by order of growth. Which pair is in the wrong order (the first grows faster than the second)?
$\log_2 n$ before $\sqrt{n}$
$n\log_2 n$ before $n$
$n^2$ before $2^n$
$\sqrt{n}$ before $n$
Explanation. The correct chain is $\log_2 n=o(\sqrt{n})$, $\sqrt{n}=o(n)$, $n=o(n\log_2 n)$, $n\log_2 n=o(n^2)$, $n^2=o(2^n)$: putting $n\log_2 n$ before $n$ reverses a pair.
A computer performs about $10^{10}$ operations per second, and a year has about $3\cdot 10^7$ seconds. An algorithm performs $2^n$ operations (with $2^{10}\approx 10^3$). How long does it take for $n=100$?
About $10$ seconds
About $4$ and a half hours
About $100$ years
About $4\cdot 10^{12}$ years
Explanation. $2^{100}=(2^{10})^{10}\approx 10^{30}$ operations, that is $10^{20}$ seconds, about $3\cdot 10^{12}$–$4\cdot 10^{12}$ years: far more than the age of the universe. With $n^2=10^4$ operations a microsecond would suffice.
$f$ is asymptotically increasing if there is $n_1$ with $f(n)<f(n+1)$ for every $n\ge n_1$. The factorial has $0!=1!=1$. What is the smallest valid $n_1$ for $f(n)=n!$?
$n_1=0$
$n_1=1$
$n_1=2$
None: $n!$ is not asymptotically increasing
Explanation. For $n=0$ the inequality $0!<1!$ is false ($1<1$); for every $n\ge 1$ we have $n!<(n+1)!=(n+1)\cdot n!$. It suffices that the property holds from some point on.
Inside $\Theta$ the base of the logarithm does not matter: $\log_a n=\log_b n/\log_b a=\Theta(\log_b n)$ for constant bases $a,b>1$. What happens if the base depends on $n$, as in $\log_n n$?
$\log_n n=1$, which is not $\Theta(\log_2 n)$
It still holds: $\log_n n=\Theta(\log_2 n)$
$\log_n n=n$
$\log_n n$ is undefined for every $n$
Explanation. $\log_n n=\log_2 n/\log_2 n=1$: the factor $1/\log_2 a$ is constant only if $a$ is constant. Here it depends on $n$ and changes the order of growth.
For logarithms the base does not matter inside $\Theta$. Does the same hold for exponentials, that is $2^n=\Theta(3^n)$?
Yes: the bases differ by a constant
Yes, because both are exponential
No: $2^n=\omega(3^n)$
No: $2^n/3^n=(2/3)^n\to 0$, so $2^n=o(3^n)$
Explanation. $3^n=2^{n\log_2 3}$: changing base multiplies the exponent by a constant, and this changes the order. For logarithms, instead, only a constant factor in front changes.
Shifting the argument of a power does not change the order of growth: $(n+1)^3=\Theta(n^3)$. Does the same hold for the factorial, that is $(n+1)!=\Theta(n!)$?
Yes: $(n+1)!$ and $n!$ differ by a constant
No: $(n+1)!/n!=n+1\to+\infty$
Yes, as for every increasing function
No: $(n+1)!=o(n!)$
Explanation. For powers $(n+1)^3/n^3\to 1$; for the factorial the ratio is $n+1$, which grows: $n!=o((n+1)!)$. Shifting is harmless only for some families of functions.
The number of entries of the input array, whatever their values.
The value of the largest number in the input.
The number of lines of pseudo-code executed on the instance $I$.
The total number of bits needed to represent the instance $I$ in binary.
Explanation. This is Definition 11.1. The number $n$ of entries of an array and the value of a number are natural parameters useful to count the steps, but the input size is measured in bits.
The input is the single natural number $n=1000$. What is the input size?
$|I|=1000$
$|I|=10$
$|I|=4$
$|I|=9$
Explanation. A natural number $n\ge 1$ requires $\lfloor\log_2 n\rfloor+1$ bits: $\lfloor\log_2 1000\rfloor+1=10$. The value $1000$ is exponential in $|I|$; $4$ is the number of decimal digits.
An algorithm receives a single natural number $n$ and executes $\Theta(n)$ steps. What is its worst-case running time as a function of $|I|$?
Exponential: $T(|I|)=2^{\Theta(|I|)}$
Linear: $T(|I|)=\Theta(|I|)$
Logarithmic: $T(|I|)=\Theta(\log_2|I|)$
Quadratic: $T(|I|)=\Theta(|I|^2)$
Explanation. For a number we have $2^{|I|-1}\le n\le 2^{|I|}-1$ (Observation 11.12): the value $n$ is exponential in the input size, and so is every number of steps $\Theta(n)$.
The input consists of two natural numbers $n,m\ge 1$ and $M=\max\{n,m\}$. Which relation holds for $|I|=(\lfloor\log_2 n\rfloor+1)+(\lfloor\log_2 m\rfloor+1)$?
$|I|=\Theta(M)$
$|I|=\Theta(\log_2 n\cdot\log_2 m)$
$|I|=\Theta(\log_2 M)$
$|I|=\Theta(n+m)$
Explanation. One of the two numbers is $M$, hence $|I|\ge\lfloor\log_2 M\rfloor+1\ge\log_2 M$; each requires at most the bits of $M$, hence $|I|\le 2(\lfloor\log_2 M\rfloor+1)$ (Observation 11.6).
Let $a[1..n]$ be an array of natural numbers with $a[i]\ge 1$ and $M=\max\{a[1],\dots,a[n]\}$. Which statement about the input size $|I|=\sum_{i=1}^n(\lfloor\log_2 a[i]\rfloor+1)$ is correct?
$|I|=\bigO\big(n(1+\log_2 M)\big)$ and $|I|=\Omega(n)$.
$|I|=\Theta(n)$ for every array, whatever the values.
$|I|=\Omega\big(n\log_2 M\big)$ for every array.
$|I|=\bigO(\log_2 M)$, since only the largest entry counts.
Explanation. Observations 11.7 and 11.8: each entry uses at most the bits of $M$ and at least one bit. $\Theta(n)$ holds only with entries of constant size; with a single large entry $n\log_2 M$ is not a lower bound.
The input is an array $a[1..n]$ and $|I|$ is the total number of bits needed to write it. Which steps prove that $|I|=\Theta(n)$ if each entry has at most $c$ bits ($c$ constant)?
It is enough that $|I|=\bigO\big(n(1+\log_2 M)\big)$ with $M$ the maximum, since $\log_2 M$ is a constant.
$|I|\le c\,n$ gives $\bigO(n)$; each entry has at least one bit, hence $\Omega(n)$; $\bigO$ and $\Omega$ together give $\Theta$.
Each entry $a[i]$ needs $\lfloor\log_2 a[i]\rfloor+1$ bits, and the limit criterion on $|I|/n$ gives $1$.
Two entries need $\Theta(\log_2\max)$ bits, and by induction $n$ entries need $\Theta(n)$ of them.
Explanation. The upper bound comes from the assumption on the bits, the lower one from the fact that each entry needs at least one bit; together they give $\Theta$. The bound $\bigO(n(1+\log_2 M))$ alone only gives $\bigO$.
When it executes $\bigO(n^k)$ steps, where $n$ is the value of the input number.
When its pseudo-code contains a constant number of nested loops.
When $T(|I|)=2^{\Theta(|I|)}$.
When its worst-case running time satisfies $T(|I|)=\bigO(|I|^k)$ for some constant $k\in\N$.
Explanation. Definition 11.11 uses the input size in bits. A number of steps polynomial in the value $n$ of a number can be exponential in $|I|$ (as for PrimalityTest); $2^{\Theta(|I|)}$ defines the exponential algorithms.
The input size $|I|$ is the total number of bits needed to write the instance in binary (a natural number $x\ge 1$ needs $\lfloor\log_2 x\rfloor+1$ bits). The input is the array $a=[6,1,3,8]$ together with the number $n=4$ of its entries. What is $|I|$?
$10$
$4$
$16$
$13$
Explanation. The entries need $3+1+2+4=10$ bits and the number $n=4=(100)_2$ needs $3$ more: $|I|=13$. Counting only the entries (without $n$) gives $10$; counting $4$ bits for each entry gives $16$.
To prove with the definition that an input size $f(n)$ is $\Theta\big(g(n)\big)$, what must be determined?
One constant $c>0$ and a threshold $n_1$ with $0\le f(n)\le c\,g(n)$ for all $n\ge n_1$: the lower bound is automatic.
The limit of $f(n)/g(n)$ as $n\to+\infty$, which must be exactly $1$ for $\Theta$ to hold.
Two constants $c_1,c_2>0$ and a threshold $n_1$ with $0\le c_1\,g(n)\le f(n)\le c_2\,g(n)$ for all $n\ge n_1$.
Two constants $c_1,c_2>0$ with $c_1\,g(n)\le f(n)\le c_2\,g(n)$ for at least one value of $n$.
Explanation. $\Theta$ requires both the upper bound ($\bigO$, constant $c_2$) and the lower bound ($\Omega$, constant $c_1$), for all $n$ from a threshold on. Any finite positive limit, not only $1$, gives $\Theta$.
The limit criterion recalled in the chapter states: if $\lim_{n\to+\infty}f(n)/g(n)=\ell$, then $f(n)=\Theta\big(g(n)\big)$. Which hypotheses does it require?
$g(n)>0$ for every $n\ge 1$, so that the ratio is defined, and $\ell\in\R_{>0}$ finite and positive.
$\ell=1$ exactly; with another finite value one only obtains $f(n)=\bigO\big(g(n)\big)$.
$f$ and $g$ asymptotically increasing, with $f(n)\le g(n)$ for every $n\ge 1$.
None: the criterion gives $\Theta$ also when the limit is $0^+$ or $+\infty$.
Explanation. With $\ell\in\R_{>0}$, for large $n$ the ratio lies between $\ell/2$ and $2\ell$, which give the constants $c_1$ and $c_2$. A limit $0^+$ gives $f=o(g)$ and a limit $+\infty$ gives $f=\omega(g)$, not $\Theta$.
The input is a single natural number $n\ge 1$, hence $|I|=\lfloor\log_2 n\rfloor+1$ (the number of bits of $n$). What is the order of growth of $|I|$ as a function of the value $n$?
$|I|=\Theta(n)$
$|I|=\Theta(1)$
$|I|=\Theta(\log_2 n)$
$|I|=\Theta(\log_2\log_2 n)$
Explanation. $\log_2 n\le\lfloor\log_2 n\rfloor+1\le 2\log_2 n$ for $n\ge 2$ (or: the ratio tends to $1$). The value $n$ instead grows exponentially with respect to $|I|$.
The input consists of the two natural numbers $n=5$ and $m=1000$, and $|I|=(\lfloor\log_2 n\rfloor+1)+(\lfloor\log_2 m\rfloor+1)$. What is $|I|$?
$13$
$10$
$20$
$1005$
Explanation. $5=(101)_2$ has $3$ bits and $1000$ has $10$ ($2^9\le 1000<2^{10}$): $|I|=13$. With $M=\max\{n,m\}$ we always have $\lfloor\log_2 M\rfloor+1\le|I|\le 2(\lfloor\log_2 M\rfloor+1)$, i.e., $|I|=\Theta(\log_2 M)$.
The input size of a natural number $n$ in binary is $\lfloor \log_2 n \rfloor+1$ bits. Knowing that this quantity is both $O(\log_2 n)$ and $\Omega(\log_2 n)$, what is concluded?
It is $\Theta(n)$
It is $\Theta(\log_2 n)$
It is $o(\log_2 n)$
Nothing, the exact constants are needed
Explanation. $O$ and $\Omega$ together are equivalent to $\Theta$. The size of $n$ grows as $\log_2 n$, not as the value $n$.
The input consists of two naturals $n=1000$ and $m=8$ written in binary. How many bits does the input size measure?
$1008$
$10$
$2$
$14$
Explanation. $1000$ needs $\lfloor\log_2 1000\rfloor+1=10$ bits and $8$ needs $4$: $14=\Theta(\log_2 n+\log_2 m)$ in total. $1008$ adds the values, not the lengths.
An algorithm is polynomial if $T(|I|)=O(|I|^k)$ for a constant $k$, where $|I|$ is the input size. Trial-division primality testing on a natural $n$ takes $\Theta(\sqrt{n})$ divisions. Which statement is correct?
It is polynomial, since $\sqrt{n}$ is a power of $n$
It is not polynomial: with $|I|=\Theta(\log_2 n)$ bits, $\sqrt{n}=2^{\Theta(|I|)}$ is exponential in the size
It is linear in the input size
It is polynomial only if $n$ is prime
Explanation. The size is the number of bits, not the value: $\sqrt{n}=2^{(\log_2 n)/2}$. A time polynomial in the numerical value is called pseudo-polynomial.
Observation: if $a_1 2^{b_1 x} \le T(x) \le a_2 2^{b_2 x}$ eventually, with positive constants, then $T(x)=2^{\Theta(x)}$. Why can one not write $T(x)=\Theta(2^x)$?
Because with $b_1 \ne b_2$ the orders differ
Because $T$ is not positive
Because $2^{\Theta(x)}$ and $\Theta(2^x)$ are the same thing
Because $a_1$ and $a_2$ differ
Explanation. $2^{2x}=4^x$ is not $\Theta(2^x)$: a constant factor in the exponent changes the base. The constants $a_1,a_2$ in front, instead, are absorbed by $\Theta$.
Let $|I|=\sum_{i=1}^{n}(\lfloor\log_2 a[i]\rfloor+1)$ be the input size of an array of naturals $a[i] \ge 1$, and $M=\max_i a[i]$. Which statement is correct?
$|I|=\Theta(n)$ always
$|I|=\Theta(\log_2 M)$
$|I|=\Theta(M)$
$|I|=\Omega(n)$ and $|I|=O(n(1+\log_2 M))$
Explanation. Every element needs at least one bit and at most $1+\log_2 M$ bits. With arbitrarily large values $|I|$ may grow faster than $n$; with bounded values it is $\Theta(n)$.
The input is a natural $n$ and an array $a[1..n]$ of naturals $a[i] \ge 1$; the size is $(\lfloor\log_2 n\rfloor+1)+\sum_i(\lfloor\log_2 a[i]\rfloor+1)$. With $n=4$ and $a=[2,3,9,1]$, what is it?
$12$
$9$
$3$
$19$
Explanation. $n=4=(100)_2$ needs $3$ bits; $2$ and $3$ need $2$ each, $9$ needs $4$, $1$ one: $9$ bits for the array. $3+9=12$ in total; $9$ forgets the number $n$, $19$ adds the values.
The input is a natural $n \ge 1$ and an array $a[1..n]$ of naturals $a[i] \ge 1$, and $M=\max\{n,a[1],\dots,a[n]\}$. Which upper bound on the input size $|I|$ (in bits) is correct?
$|I|=O(\log_2 M)$
$|I|=O(n)$ always
$|I|=O((n+1)(1+\log_2 M))$
$|I|=O(M)$ and nothing better
Explanation. Each of the $n+1$ numbers needs at most $1+\log_2 M$ bits. $O(n)$ holds only if the values have fixed size; $O(M)$ is true but much weaker.
The input size $|I|$ is the number of bits needed to write the instance (a natural $x\ge 1$ needs $\lfloor\log_2 x\rfloor+1$). One compares the instance made of the single number $n=10^6$ and the array of $10^6$ components equal to $1$. What are their sizes?
$10^6$ bits in both cases
$20$ bits in both cases
$20$ bits and $10^6$ bits
$10^6$ bits and $20$ bits
Explanation. $\lfloor\log_2 10^6\rfloor+1=20$; the array has $10^6$ components of $1$ bit each. The same «$10^6$» gives very different sizes: what counts is how many bits are needed, not how large the number is.
For an instance made of a single natural number $n$, why is the input size $\Theta(\log n)$ and not $n$?
Because $n$ is written with $\lfloor\log_2 n\rfloor+1$ bits, and the size counts bits
Because numerical algorithms always perform $\log n$ steps
Because $n$ is one value, and the size counts values
Because base $10$ needs $\log_{10} n$ digits, and base $10$ is used
Explanation. The size measures the length of the binary representation of the instance. Counting values would give $1$ for every $n$; the base does not change the order $\Theta(\log n)$, but the definition uses bits.
One wants to prove from the definition that $f(n)=\lfloor\log_2 n\rfloor+1=\Theta(\log_2 n)$, that is $c_1\log_2 n\le f(n)\le c_2\log_2 n$ for every $n\ge n_1$. Which choice works?
$c_1=1$, $c_2=2$, $n_1=1$
$c_1=2$, $c_2=2$, $n_1=2$
$c_1=1$, $c_2=2$, $n_1=2$
$c_1=1$, $c_2=1$, $n_1=2$
Explanation. $\lfloor x\rfloor+1>x$ gives the lower bound with $c_1=1$; $\lfloor\log_2 n\rfloor+1\le 2\log_2 n$ holds if $\log_2 n\ge 1$, that is $n\ge 2$. For $n=1$ one would get $1\le 0$; with $c_2=1$ already $n=2$ fails ($2\le 1$).
A natural number $n\ge 1$ is written in binary with $\lfloor\log_2 n\rfloor+1$ bits. How many binary digits do $255$ and $256$ have?
$8$ and $9$
$8$ and $8$
$9$ and $9$
$7$ and $8$
Explanation. $255=2^8-1=(11111111)_2$ has $8$ bits, $256=2^8$ is a $1$ followed by $8$ zeros: $9$ bits. The number of bits grows at every power of $2$.
A primality test receives the single natural $n$ and performs, in the worst case, about $\sqrt n$ divisions. Let $x=|I|=\Theta(\log n)$ be the input size. How does the number of divisions grow as a function of $x$?
Like $\Theta(\sqrt x)$: sub-linear in $x$
Like $\Theta(x)$: linear in $x$
Like $\Theta(x^2)$: polynomial in $x$
Like $2^{\Theta(x)}$: exponential
Explanation. $n\approx 2^x$, so $\sqrt n\approx 2^{x/2}=2^{\Theta(x)}$. Time must be expressed as a function of the input size, not of the value $n$: a «$\sqrt n$» algorithm on a number is not polynomial.
The input consists of two naturals $n,m\ge 2$, with $|I|=(\lfloor\log_2 n\rfloor+1)+(\lfloor\log_2 m\rfloor+1)$. Which expression is also $\Theta(|I|)$?
$\log_2 n\cdot\log_2 m$
$\log_2(n\cdot m)$
$n+m$
$\sqrt{n\cdot m}$
Explanation. $\log_2(nm)=\log_2 n+\log_2 m$, which differs from $|I|$ by at most $2$ and is at least $|I|/2$ for $n,m\ge 2$. The product of the logarithms grows like $(\log n)^2$ for $n=m$; $n+m$ and $\sqrt{nm}$ are exponential in $|I|$.
For an array $a[1..n]$ of naturals $a[i]\ge 1$, $|I|=\sum_i(\lfloor\log_2 a[i]\rfloor+1)$ and, with $M=\max_i a[i]$, $|I|\le n\,(\lfloor\log_2 M\rfloor+1)$. With $a=[100,1,1,1]$, what are $|I|$ and the upper bound?
$|I|=28$, bound $28$
$|I|=10$, bound $10$
$|I|=7$, bound $28$
$|I|=10$, bound $28$
Explanation. $100$ has $7$ bits and each $1$ has one: $|I|=7+3=10$. The bound treats every component as the largest: $4\cdot 7=28$. It is an upper bound, not always tight.
An algorithm receives an array $a[1..n]$ of naturals, with $M=\max_i a[i]$, and performs $\Theta(n\cdot M)$ steps in the worst case. The input size is $|I|=\Theta(n\log M)$. Is the algorithm polynomial (steps $\bigO(|I|^k)$ for a constant $k$)?
Yes: $n\cdot M$ is a product, that is a polynomial
No: for fixed $n$, $M$ can be $2^{\Theta(|I|)}$
Yes: the number of steps is linear in $n$
Yes: $n\cdot M\le|I|^2$ for every input
Explanation. With $n=1$ we have $|I|=\Theta(\log M)$ and the steps are $\Theta(M)=2^{\Theta(|I|)}$: exponential in the size. The value of the numbers, unlike the number of components, can be exponential in the length of their encoding.
Which assumption is made on the primitive operations to count the steps of an algorithm?
Each operation requires a time proportional to the number of bits of its operands, also for fixed-size numbers.
Arithmetic operations require constant time, comparisons and assignments do not.
Each primitive operation requires constant time, and one step is counted for each execution of a line of pseudo-code.
Only key comparisons are counted, the other operations have zero cost.
Explanation. Assuming constant time for each primitive operation makes the analysis machine-independent; counting a line as one step changes the total only by a constant factor.
FindMaximum sets $max:=a[1]$ and, for $i=2,\dots,n$, executes $max\leftarrow a[i]$ if $a[i]>max$; with one step per executed line it makes $3n+1+t$ steps, where $t$ counts the assignments $max\leftarrow a[i]$. On which input does it reach the maximum, $4n$?
On a strictly decreasing array
On an array with all elements equal
On a strictly increasing array
On an array with the maximum in the first position
Explanation. The steps are $3n+1+t$, where $t$ is the number of executions of $max\leftarrow a[i]$: $t=n-1$ when every element is a new maximum, i.e., for a strictly increasing array.
In the worst case InsertionSort executes $S(n)=\frac{3n^2+9n-8}{2}$ steps on an array of $n$ entries of constant size. What is its worst-case running time as a function of the input size $|I|$ (number of bits of the instance)?
$T(|I|)=\Theta(|I|^2)$
$T(|I|)=\Theta(|I|)$
$T(|I|)=2^{\Theta(|I|)}$
$T(|I|)=\Theta(\log_2^2|I|)$
Explanation. $S(n)=\Theta(n^2)$ and, with entries of constant size, $|I|=\Theta(n)$: substituting we get $\Theta(|I|^2)$.
In the worst case PrimalityTest executes $S(n)=3\lfloor\sqrt n\rfloor+1$ steps on the natural number $n$. What is its worst-case running time as a function of the input size $|I|$ (number of bits of $n$)?
$T(|I|)=\Theta(\sqrt{|I|})$
$T(|I|)=\Theta(|I|)$
$T(|I|)=\Theta(|I|^2)$
$T(|I|)=2^{\Theta(|I|)}$
Explanation. $|I|=\Theta(\log_2 n)$, i.e., $n=2^{\Theta(|I|)}$, hence $\sqrt n=2^{\Theta(|I|)/2}$, which is still $2^{\Theta(|I|)}$: the algorithm is exponential in the input size.
ChangeToBase2 executes $S(n)=6\lfloor\log_2 n\rfloor+11$ steps on the natural number $n$. What is its worst-case running time as a function of the input size $|I|$ (number of bits of $n$)?
$T(|I|)=\Theta(\log_2|I|)$
$T(|I|)=\Theta(|I|)$
$T(|I|)=2^{\Theta(|I|)}$
$T(|I|)=\Theta(|I|\log_2|I|)$
Explanation. The number of steps is proportional to the number of binary digits of $n$, which is exactly $|I|=\lfloor\log_2 n\rfloor+1$: the running time is linear in the input size.
An algorithm executes $S(n)$ steps; the running time $T(|I|)$ expresses the steps as a function of the input size $|I|$ (number of bits). Which statement is correct?
If $n$ is the value of the input number, $S(n)=\Theta(n)$ gives $T(|I|)=\Theta(|I|)$, as for an array.
The order of growth never changes from $S(n)$ to $T(|I|)$, whatever the meaning of $n$.
If $n$ is the value of the input number, also $S(n)=\Theta(\log_2 n)$ is exponential in $|I|$.
If $n$ is the value of the input number, $S(n)=\Theta(\log_2 n)$ is linear in $|I|$ and $S(n)=\Theta(n)$ is exponential.
Explanation. For an array $|I|=\Theta(n)$; for a number $|I|=\Theta(\log_2 n)$, i.e., $n=2^{\Theta(|I|)}$. This is why $\Theta(\log_2 n)$ steps are linear in $|I|$ and $\Theta(\sqrt n)$ or $\Theta(n)$ steps are exponential.
InsertionSort executes $S(n)=\Theta(n^2)$ steps on an array of $n$ entries; we want to conclude $T(|I|)=\Theta(|I|^2)$, where $|I|$ is the number of bits of the input. What is needed?
Nothing else: $S(n)=\Theta(n^2)$ is already the running time as a function of $|I|$.
The relation $|I|=\Theta(n)$, valid with entries of constant size and the constants of the definitions of $\Theta$.
The relation $|I|=\Theta(\log_2 n)$, valid when the input is a natural number $n$.
The limit criterion applied to the ratio $S(n)/n$, which diverges.
Explanation. From $a_1 n^2\le S(n)\le a_2 n^2$ and $c_1|I|\le n\le c_2|I|$ we get $a_1c_1^2|I|^2\le S(n)\le a_2c_2^2|I|^2$. Without the relation between $n$ and $|I|$ the step is not justified.
FindMaximum sets $max:=a[1]$ and, for $i=2,\dots,n$, executes $max\leftarrow a[i]$ if $a[i]>max$; counting one step per executed line it performs $3n+1+t$ steps, where $t$ is the number of assignments $max\leftarrow a[i]$. On which arrays of $n$ elements does it perform the minimum, $3n+1$ steps?
Only on strictly increasing arrays, where the maximum is the last element
On those in which the maximum appears only once, in any position
On those with the maximum in the last position, where a single assignment is needed
On those in which $a[1]$ is a maximum element, for instance with all elements equal
Explanation. $t=0$ exactly when no $a[i]$, $i\ge 2$, is strictly larger than the current maximum, i.e., when $a[1]\ge a[i]$ for every $i$. On strictly increasing arrays one gets instead the maximum, $t=n-1$.
ChangeToBase2 is run with $n=100$. Counting one step for each execution of a numbered line (the while condition counts at each evaluation), how many steps does it perform? <pre>1 nd := ⌊log₂ n⌋ + 1
2 d := new array[0..nd−1]
3 k := 0
4 <b>while</b> n > 0 <b>do</b>
5 q := ⌊n / 2⌋
6 r := n mod 2
7 d[k] ← r
8 n ← q
9 k ← k + 1
<b>end</b>
10 <b>return</b> d, nd</pre>
$46$
$47$
$53$
$41$
Explanation. $100$ has $\lfloor\log_2 100\rfloor+1=7$ binary digits, so the body (lines $5$–$9$) is executed $7$ times and the condition $8$ times: $3+8+5\cdot 7+1=47=6\lfloor\log_2 n\rfloor+11$. Forgetting the last evaluation of the condition gives $46$.
PrimalityTest is run with $n=91=7\cdot 13$. Counting one step for each execution of a numbered line (the while condition counts at each evaluation), how many steps does it perform? <pre>1 <b>if</b> n < 2 <b>then</b>
2 <b>return</b> false
<b>end</b>
3 d := 2
4 <b>while</b> d ≤ ⌊√n⌋ <b>do</b>
5 <b>if</b> n mod d = 0 <b>then</b>
6 <b>return</b> false
<b>end</b>
7 d ← d + 1
<b>end</b>
8 <b>return</b> true</pre>
$28$
$19$
$26$
$20$
Explanation. Lines $1$ and $3$ once; for $d=2,\dots,7$ the condition (line $4$) and the test (line $5$) are evaluated: $6+6$; for $d=7$ the test is true and line $6$ returns false; line $7$ is executed for $d=2,\dots,6$: $5$. Total $1+1+12+1+5=20$. $28=3\lfloor\sqrt{91}\rfloor+1$ holds only for a prime.
In the worst case FindMaximum performs $4n$ steps and InsertionSort $\frac{3n^2+9n-8}{2}$ (with $n$ entries of the array, of constant size), ChangeToBase2 $6\lfloor\log_2 n\rfloor+11$ and PrimalityTest $3\lfloor\sqrt n\rfloor+1$ (with $n$ the value of the input number). Which of these algorithms is exponential in the input size $|I|$?
InsertionSort
PrimalityTest
ChangeToBase2
FindMaximum
Explanation. For an input number $|I|=\Theta(\log_2 n)$, i.e., $n=2^{\Theta(|I|)}$, and $\sqrt n=2^{\Theta(|I|)}$. The others are polynomial: $\Theta(|I|)$, $\Theta(|I|^2)$ and $\Theta(|I|)$.
In the course, the running time of an algorithm is defined as…
the time in seconds measured on a reference computer
the number of lines of the pseudo-code
an estimate of the number of executed steps, as a function of the input size $|I|$
the memory used by the algorithm
Explanation. Time in seconds depends on computer, compiler and language; counting steps as a function of $|I|$ makes the analysis independent of these details.
Which of the following is not a primitive operation (cost of one step) in the course's model?
Adding two numbers of fixed size
Comparing two numbers of fixed size
Reading $a[i]$ given the index $i$
Sorting an array of $n$ elements
Explanation. Primitive operations have constant cost: arithmetic and comparisons on fixed-size numbers, access to an element given its index, assignments. Sorting an array takes many steps.
FindMaximum$(a[1..n])$ sets $max:=a[1]$, then for $i=2,\dots,n$ runs «if $a[i]>max$ then $max:=a[i]$», and returns $max$. How many times is the condition of the for loop (the test deciding whether to run another iteration) evaluated?
$n-1$ times
$n$ times
$n+1$ times
It depends on the values of the array
Explanation. The body runs for $i=2,\dots,n$, that is, $n-1$ times, and the condition is evaluated once more, when it fails: $n$ times. Only the number of executions of $max:=a[i]$ depends on the values.
FindMaximum$(a[1..n])$ sets $max:=a[1]$, then for $i=2,\dots,n$ runs «if $a[i]>max$ then $max:=a[i]$», and returns $max$. On which array of $n$ distinct elements is the assignment $max:=a[i]$ executed the largest number of times (worst case)?
On an array sorted decreasingly
On an array with the maximum in first position
The number of assignments is always the same
On an array sorted increasingly, where it runs at every iteration
Explanation. In an increasing array every $a[i]$ exceeds the current maximum, so $t(i)=1$ for every $i$; in a decreasing array the maximum is $a[1]$ and the assignment never runs.
For FindMaximum the worst-case number of steps is $S(n)=\Theta(n)$ as a function of the number $n$ of elements. To conclude that the time is $O(|I|)$ as a function of the input size $|I|$ (in bits), which fact is needed?
$|I|=\Omega(n)$, hence $n=O(|I|)$
$|I|=O(n)$, since the elements have fixed size
$|I|=\Theta(\log_2 n)$
That the array is sorted
Explanation. From $|I| \ge c\,n$ it follows $n \le |I|/c$ and so $S(n) \le a\,n \le (a/c)\,|I|$. The upper bound on $|I|$ is not needed for an upper bound on the time.
An algorithm on an array $a[1..n]$ performs $S(n)=\Theta(n)$ steps, and the array elements have fixed size (a constant number of bits). What is the running time as a function of the input size $|I|$?
$\Theta(|I|^2)$
$\Theta(\log_2 |I|)$
$\Theta(|I|)$
$\Theta(2^{|I|})$
Explanation. With fixed-size elements $|I|=\Theta(n)$, so $S=\Theta(|I|)$: linear both in $n$ and in $|I|$.
InsertionSort on $a[1..n]$: for $i=2,\dots,n$ it inserts $a[i]$ into the already sorted part $a[1..i-1]$, shifting right by one position the larger elements (inner loop). In the worst case (array sorted decreasingly), how many times in total is the body of the inner loop executed with $n=6$?
$15$
$21$
$6$
$36$
Explanation. At iteration $i$ all the $i-1$ previous elements are shifted: $t(i)=i-1$, and $\sum_{i=2}^{6}(i-1)=1+2+3+4+5=15=n(n-1)/2$. $21=n(n+1)/2$ counts one more iteration for every $i$.
InsertionSort on $a[1..n]$: for $i=2,\dots,n$ it inserts $a[i]$ into the already sorted part $a[1..i-1]$, shifting right by one position the larger elements (inner loop). Let $t(i)$ be the number of executions of the inner loop body at iteration $i$. Which statement about the number of steps $S(n)$ of InsertionSort is correct?
$S(n)=\Theta(n^2)$ on every input
$S(n)=\Theta(n\log_2 n)$ in the worst case
Worst $\Theta(n^2)$ ($t(i)=i-1$), best $\Theta(n)$ ($t(i)=0$)
In the best case the steps are $\Theta(n^2)$
Explanation. The sum $\sum_{i=2}^{n}(i-1)=n(n-1)/2$ gives the quadratic term of the worst case; on a sorted array the inner loop condition fails at once in every iteration.
For InsertionSort the worst-case number of steps is $S(n)=\Theta(n^2)$. How is $S=O(|I|^2)$ obtained, with $|I|$ the input size in bits?
From $|I|=\Theta(\log_2 n)$
From $|I| \le n$
It cannot be: the time as a function of $|I|$ is exponential
From $|I| \ge c\,n$: $S \le a\,n^2 \le (a/c^2)\,|I|^2$
Explanation. The lower bound $|I|=\Omega(n)$ suffices, giving $n=O(|I|)$; squaring gives the bound on $S$. $|I|=\Theta(\log_2 n)$ concerns a single number, not an array.
InsertionSort takes $\Theta(n^2)$ steps in the worst case on an array of $n$ fixed-size elements. How is it classified with respect to the input size $|I|$?
It is exponential in $|I|$
It is a polynomial algorithm, quadratic in $|I|$
It is linear in $|I|$
It is logarithmic in $|I|$
Explanation. With fixed-size elements $|I|=\Theta(n)$, so $\Theta(n^2)=\Theta(|I|^2)$: a power of $|I|$, that is, polynomial time.
ChangeToBase2$(n)$ repeats, while $n>0$, «write the digit $n \bmod 2$; $n:=\lfloor n/2\rfloor$». How many times is the loop body executed with $n=100$?
$6$
$50$
$7$
$100$
Explanation. One iteration per binary digit: $\lfloor\log_2 100\rfloor+1=6+1=7$ ($100=(1100100)_2$). $50$ would count as if $n$ decreased by $2$ at every step.
ChangeToBase2$(n)$ repeats, while $n>0$, «write the digit $n \bmod 2$; $n:=\lfloor n/2\rfloor$». After $s$ iterations the current value is $\lfloor n/2^s\rfloor$. Why does the loop run exactly $\lfloor\log_2 n\rfloor+1$ times?
Because $\lfloor n/2^s\rfloor=0$ exactly when $2^s>n$, and the smallest such $s$ is $\lfloor\log_2 n\rfloor+1$
Because $n$ is a power of $2$
Because every iteration halves the number of decimal digits
Because $\lfloor n/2^s\rfloor$ is always odd
Explanation. The loop stops at the first $s$ with value $0$, that is, with $2^s>n$; for every $n \ge 1$ it is $s=\lfloor\log_2 n\rfloor+1$, the number of binary digits. $n$ need not be a power of $2$.
ChangeToBase2 on a natural $n$ performs $\Theta(\log_2 n)$ steps, and the input is $n$ written in base $10$. Which statement about the time as a function of the input size $|I|$ is correct?
$|I|=\Theta(n)$, so the time is logarithmic in $|I|$
The time is exponential in $|I|$
$|I|=\Theta(\log_{10} n)=\Theta(\log_2 n)$, so the time is $\Theta(|I|)$: linear
Changing the base of logarithms changes the order of growth
Explanation. The number of decimal digits is $\Theta(\log_{10} n)$, and $\log_{10} n=\log_2 n/\log_2 10$ differs from $\log_2 n$ by a constant. So steps and size have the same order.
A natural $n$ is given as input written in base $10$. Doubling the number of decimal digits of $n$, what happens to the number of steps of ChangeToBase2 (which runs one iteration per binary digit of $n$)?
It roughly doubles
It gets squared
It stays the same
It becomes exponentially larger
Explanation. The number of binary digits is about $\log_2 10 \approx 3.32$ times the number of decimal digits, so the steps grow linearly with the input size.
PrimalityTest$(n)$, for $n \ge 2$, tries the divisors $d=2,3,\dots$ while $d \cdot d \le n$, and returns «composite» as soon as $n \bmod d=0$, otherwise «prime». With $n=101$ (prime), how many times is the loop body executed?
$10$
$99$
$50$
$9$
Explanation. $d$ takes the values $2,\dots,\lfloor\sqrt{101}\rfloor=10$: $10-1=9$ iterations, with no early exit since $101$ is prime. $99$ would try every $d<n$.
PrimalityTest$(n)$, for $n \ge 2$, tries the divisors $d=2,3,\dots$ while $d \cdot d \le n$, and returns «composite» as soon as $n \bmod d=0$, otherwise «prime». For which inputs does the worst case (the largest number of steps for a given $n$) occur?
When $n$ is even
When $n$ is prime: the loop never exits early
When $n$ is a perfect square
The number of steps does not depend on $n$
Explanation. A composite has a divisor $\le \sqrt{n}$ and the test exits as soon as it finds it (immediately, if $n$ is even); a prime forces trying every $d$ up to $\lfloor\sqrt{n}\rfloor$.
PrimalityTest$(n)$, for $n \ge 2$, tries the divisors $d=2,3,\dots$ while $d \cdot d \le n$, and returns «composite» as soon as $n \bmod d=0$, otherwise «prime». The worst-case steps are $\Theta(\sqrt{n})$ and the input size is $|I|=\Theta(\log_2 n)$. Which step proves that the time is exponential in $|I|$?
$\sqrt{n}$ is a power of $n$, so it is polynomial
$\log_2 n \le n$
The constants $c_1$ and $c_2$ can be ignored in the exponent
From $c_1\log_2 n \le |I| \le c_2\log_2 n$ one gets $2^{|I|/c_2} \le n \le 2^{|I|/c_1}$, so $\sqrt{n}=2^{\Theta(|I|)}$
Explanation. Applying the increasing function $2^x$ to the inequalities expresses $n$ in terms of $|I|$; the constants end up in the exponent, where they cannot be dropped: one writes $2^{\Theta(|I|)}$.
Trial-division primality testing takes $\Theta(\sqrt{n})$ steps on a natural $n$ written in binary. Adding $2$ bits to the input size (that is, multiplying $n$ by about $4$), what happens to the number of steps?
It grows by $2$
It roughly doubles
It stays the same
It grows by about $2\%$
Explanation. $\sqrt{4n}=2\sqrt{n}$: two more bits double the steps, that is, every extra bit multiplies them by $\sqrt2$. This is the behaviour of a time exponential in the size.
In the step count of a pseudo-code every executed line costs one step. A loop «for $i=1$ to $n$» with a one-line body: how many steps does it cost in total (body lines plus evaluations of the for condition)?
$2n+1$
$n$
$2n$
$n+1$
Explanation. The condition is evaluated $n+1$ times (the last one fails) and the body $n$ times: $2n+1$. Forgetting the last evaluation gives $2n$.
An algorithm on arrays of $n$ elements performs $3n$ steps on some inputs and $n^2$ steps on others, always with $n$ elements. What is its worst-case running time?
$\Theta(n)$
$\Theta((n^2+3n)/2)$, the average
$\Theta(n^2)$
It is undefined, since it depends on the input
Explanation. The worst case is the maximum number of steps over the inputs of the same size: $n^2$ for $n \ge 3$. The average would need a distribution of the inputs.
Why is the running time of an algorithm expressed with an asymptotic notation, such as $\Theta(n^2)$, instead of an exact formula?
Because the exact formula never exists
Because modern computers have constant time
Because only the best case matters
Because constants depend on the computer, the order does not
Explanation. Counting a line as one step is a convention: another count changes the constants, not the order of growth, which is what compares algorithms on large inputs.
The worst-case running time is the largest number of steps over all inputs of size $n$. If it were measured only on one «typical» input of each size, what would be lost?
Nothing: all inputs of size $n$ cost the same
The guarantee: other inputs may need more steps
Only the multiplicative constants
The possibility of using $\bigO$ notation
Explanation. For instance Insertion Sort on a sorted array makes $\Theta(n)$ steps, on a decreasing one $\Theta(n^2)$. The worst case is a bound valid for every input.
When counting steps one assumes that every elementary operation (for instance an addition) costs constant time. When must this hypothesis be revised?
Never: an addition always costs $\Theta(1)$
When the algorithm is recursive
When the input is an array
When the numbers grow with the input
Explanation. An addition on fixed-size numbers (for instance <code>int</code>) is constant; if the operands have $k$ bits with $k$ growing, an addition costs $\Theta(k)$, as in computations on $n!$ or $2^n$.
A variable whose value never changes during the execution of the loop, from the first to the last iteration.
A property that is true only at the end of the loop, when the condition becomes false.
A property of the variables that is true every time the condition of the loop is evaluated: before the first iteration and after each iteration.
A property that is true at every moment of the execution of the body of the loop.
Explanation. This is Definition 13.2: during the body the invariant may be temporarily false, as long as it is true again when the condition is evaluated.
Which three properties are proved in order to use a loop invariant?
Initialization, maintenance and termination
Base case, inductive step and inductive hypothesis
Declaration, assignment and return
Termination, optimality and stability
Explanation. Initialization: it holds before the first iteration; maintenance: if it holds before an iteration it holds after it; termination: when the loop ends, the invariant gives the desired result.
FindMaximum sets $max:=a[1]$, $i:=2$ and, while $i\le n$, executes $max\leftarrow a[i]$ if $a[i]>max$ and then $i\leftarrow i+1$. Which loop invariant (true at every evaluation of the condition) proves its correctness?
$max=\max\{a[1],\dots,a[i]\}$
$max=a[i-1]$
$max=\max\{a[1],\dots,a[i-1]\}$
$max\ge a[i]$
Explanation. Before the first iteration $i=2$ and $max=a[1]=\max\{a[1]\}$; each iteration compares $a[i]$ and increments $i$; at the end $i=n+1$ and $max=\max\{a[1],\dots,a[n]\}$. With $a[1..i]$ the initialization fails.
BinarySearch looks for $m$ in $a[1..n]$ sorted in non-decreasing order, examining the central element of the current interval and returning an index or $-1$. Which statement about its correctness is true?
The algorithm terminates and returns an index $k$ with $a[k]=m$ if $m$ is in the array, and $-1$ otherwise.
The algorithm always returns the smallest index $k$ with $a[k]=m$.
The algorithm is correct only if the elements of the array are distinct.
The algorithm terminates only if $m$ is in the array.
Explanation. This is Observation 13.6. With repeated values some index with $a[k]=m$ is returned, not necessarily the first one; if $m$ is absent, the interval becomes empty and the algorithm returns $-1$.
InsertionSort, for $i=2,\dots,n$, inserts $\mathit{key}=a[i]$ into the prefix $a[1..i-1]$ with an inner loop that shifts the larger keys to the right. What is used to prove its correctness?
The correctness of FindMaximum applied to each prefix $a[1..i]$: the maximum always ends in position $i$.
The number of comparisons, at most $\frac{n(n-1)}{2}$, which guarantees both termination and sorting.
The outer invariant «$a[1..i-1]$ is sorted, with the original elements» and a lemma on the inner loop for maintenance.
The invariant of the merge of two sorted subarrays, applied to the prefixes $a[1..i-1]$ and $a[i..i]$.
Explanation. The lemma on the inner loop says that, if $a[1..i-1]$ is sorted, after the inner loop and the insertion of $\mathit{key}$ the sub-array $a[1..i]$ is sorted: this is exactly the maintenance of the invariant of the outer loop.
The Euclidean algorithm, starting from $(n,m)=(n_0,m_0)$, replaces $(n,m)$ with $(m,\,n\bmod m)$ while $m\ne 0$ and returns $n$. What is the proof of its correctness based on?
On the fact that if $d$ divides $n$ then $n/d$ divides $n$, and one of the two is at most $\sqrt n$.
On the invariant $\gcd(n,m)=\gcd(n_0,m_0)$, maintained by $\gcd(n,m)=\gcd(m,n\bmod m)$, and on $m$ decreasing.
On the fact that every composite $n$ has a divisor $d$ with $2\le d\le\lfloor\sqrt n\rfloor$.
On the invariant «$m\le n$», true before every iteration, and on $n$ decreasing.
Explanation. Maintenance uses $\gcd(n,m)=\gcd(m,n\bmod m)$, termination the fact that $r<m$. The invariant $m\le n$ is false at the beginning if $n_0<m_0$.
The correctness of FindMaximum ($max:=a[1]$, $i:=2$; while $i\le n$: if $a[i]>max$ then $max\leftarrow a[i]$; $i\leftarrow i+1$) uses the invariant $max=\max\{a[1],\dots,a[i-1]\}$. What does the termination property give?
The loop ends with $i=n+1$; substituting into the invariant gives $max=\max\{a[1],\dots,a[n]\}$.
The loop ends with $i=n$; the invariant gives $\max\{a[1],\dots,a[n-1]\}$ and a last comparison is needed.
Termination follows from the fact that $max$ strictly increases at every iteration of the loop.
The loop ends when $max=a[n]$, i.e., when the last element is the maximum.
Explanation. $i$ increases by $1$ at every iteration, so the loop ends when the condition $i\le n$ becomes false, with $i=n+1$: the invariant with the negated condition gives the output. $max$ does not change when $a[i]\le max$.
In iteration $i=5$ of InsertionSort the prefix is $a[1..5]=[1,2,4,5,3]$ and $\mathit{key}=a[5]=3$. The inner loop starts from $j=4$ and, while $j\ge 1$ and $a[j]>\mathit{key}$, executes $a[j+1]\leftarrow a[j]$ and $j\leftarrow j-1$; then $a[j+1]\leftarrow\mathit{key}$. With which value of $j$ does the inner loop end, and in which position does $\mathit{key}$ go?
$j=3$; $\mathit{key}$ goes to $a[3]$
$j=2$; $\mathit{key}$ goes to $a[2]$
$j=2$; $\mathit{key}$ goes to $a[3]$
$j=1$; $\mathit{key}$ goes to $a[2]$
Explanation. $a[4]=5$ and $a[3]=4$ are larger than $3$ and are shifted to the right; with $j=2$ we have $a[2]=2\le 3$ and the loop ends. Position $j+1=3$ is the «hole» of the invariant, and the array becomes $[1,2,3,4,5]$.
BinarySearch looks for $m$ in the sorted array $a[1..n]$ with a while loop of condition $left\le right$, shrinking the interval $a[left..right]$. Which invariant (true at each evaluation of the condition) proves its correctness?
$a[left]\le m\le a[right]$, so that $m$ always lies between the ends of the interval
$1\le left$, $right\le n$ and, if $m$ is in the array, then $m$ is in $a[left..right]$
The interval $a[left..right]$ contains exactly $n/2^k$ elements after $k$ iterations
$m=a[mid]$ for the middle index $mid$ of the current interval $a[left..right]$
Explanation. The algorithm never discards a part that may contain $m$. If $m$ is missing, $a[left]\le m\le a[right]$ may be false from the start; when the interval becomes empty the invariant guarantees that $-1$ is correct.
The Euclidean algorithm, while $m\ne 0$, replaces $(n,m)$ with $(m,\,n\bmod m)$ and then returns $n$; its correctness uses the invariant $\gcd(n,m)=\gcd(n_0,m_0)$ ($n_0,m_0\ge 1$ initial values). Why does the loop terminate?
Because $n$ decreases by at least $1$ at every iteration and always stays greater than or equal to $m$.
Because the value of $\gcd(n,m)$ strictly decreases at every iteration, until it reaches $1$.
Because $n_0\ge m_0$ is assumed: without this hypothesis the loop might not terminate.
Because $m$ is a natural number that strictly decreases ($n\bmod m<m$): after at most $m_0$ iterations $m=0$.
Explanation. The remainder $r=n\bmod m$ satisfies $0\le r<m$. The $\gcd$ instead never changes (it is the invariant), and with $n_0<m_0$ the first iteration just swaps the two numbers.
BadSum$(a,l,r)$ returns $a[l]$ if $l=r$; otherwise it sets $m:=\lceil(l+r)/2\rceil$ and returns BadSum$(a,l,m)+$BadSum$(a,m+1,r)$. What happens when calling BadSum$(a,1,2)$?
It correctly returns $a[1]+a[2]$, like the version with $\lfloor(l+r)/2\rfloor$.
The recursion does not terminate: with $m=2$ the first call is again BadSum$(a,1,2)$.
It returns only $a[1]$, because the second call is on an empty interval.
It stops with an index error, because the second call uses $m+1=3>r$.
Explanation. $\lceil 3/2\rceil=2$, so BadSum$(a,1,2)$ calls itself on the same instance: the proof by induction requires every call to be on a strictly smaller instance, and this is exactly what is missing here.
One proves by induction on the size of the instance that a recursive algorithm is correct. In the inductive step, what is assumed?
That the algorithm returns the correct output on the current instance, the one to be handled.
That the algorithm terminates on every instance, without the need to prove it separately.
That the recursion is a tail recursion, so that it can be turned into a loop with an invariant.
That the recursive calls, made on smaller instances, return the correct output.
Explanation. Inductive hypothesis: correctness on the smaller instances; one proves that the algorithm combines their results into the correct output. Assuming correctness on the current instance would be circular.
An algorithm is correct if, on every instance of the problem, it terminates and returns the right output. To establish that an algorithm is correct, is it enough to test it on many inputs?
Yes, if at least $1000$ random inputs are tested
No: tests find errors, but correctness must be proved
Yes, if the best and the worst case are tested
Yes, if all instances of size at most $10$ are tested
Explanation. Instances are infinitely many: a finite set of tests, however large, does not cover them. This is why loop invariants and induction are used.
FindMaximum sets $max:=a[1]$, $i:=2$ and, while $i\le n$, updates $max$ with $a[i]$ if larger and increments $i$. The invariant is «$max=\max(a[1..i-1])$». Why does it hold before the first iteration (initialisation)?
Because $i=2$ and $max=a[1]=\max(a[1..1])$
Because $max$ is the largest element of the array from the start
Because $a[1..i-1]$ is empty when $i=2$
Because at exit $i=n+1$
Explanation. With $i=2$ the prefix $a[1..i-1]$ is $a[1..1]$, whose maximum is $a[1]$. Exit with $i=n+1$ serves instead for termination, to conclude $max=\max(a[1..n])$.
For FindMaximum ($max:=a[1]$, $i:=2$; while $i\le n$: if $a[i]>max$ then $max\leftarrow a[i]$; $i\leftarrow i+1$) a student proposes the invariant «$max=\max(a[1..i])$», evaluated before each check of the condition. What is wrong?
Nothing: it is equivalent to the invariant with $\max(a[1..i-1])$
It holds at the start, but does not give the result at exit
It fails at the start, if $a[2]>a[1]$
It is not maintained, because $max$ never changes
Explanation. Before examining $a[i]$ the algorithm knows only $a[1..i-1]$. On $a=[3,7]$: with $i=2$, $max=3$ but $\max(a[1..2])=7$. The correct invariant uses $a[1..i-1]$.
In the inner loop of InsertionSort (iteration $i$, $\mathit{key}=b[i]$, where $b[1..i]$ is $a[1..i]$ at the start of the iteration), while $j\ge 1$ and $a[j]>\mathit{key}$, $a[j]$ is moved to $a[j+1]$. Which property is part of the invariant, at each check of the condition?
The whole prefix $a[1..i]$ is already sorted
The cell $a[j+1]$ already holds $\mathit{key}$
Every element of $a[1..j]$ is greater than $\mathit{key}$
Every element of $a[j+2..i]$ is greater than $\mathit{key}$
Explanation. The elements already moved right are those greater than $\mathit{key}$; $a[1..j]$ has not been touched and $a[j+1]$ is the «hole» where $\mathit{key}$ will go. $a[1..i]$ is sorted only after the insertion.
The outer-loop invariant of InsertionSort says that, at the start of iteration $i$, $a[1..i-1]$ holds the elements originally in $a[1..i-1]$, sorted. Starting from $[5,2,4,6,1,3]$, what does $a[1..4]$ hold after iteration $i=4$?
$[1,2,3,4]$
$[2,4,5,6]$
$[2,5,4,6]$
$[1,2,4,5]$
Explanation. After iteration $4$ the invariant holds with $i=5$: the first four original elements $5,2,4,6$, in order. The four smallest keys ($[1,2,3,4]$) are instead the property of Selection Sort.
BinarySearch looks for $m$ in the sorted array $a[1..n]$: while $left\le right$ it examines $mid=left+\lfloor(right-left)/2\rfloor$ and, if $a[mid]\ne m$, sets $right=mid-1$ or $left=mid+1$. Why does the loop terminate?
Because $m$ is always in the sorted array
Because $mid$ stays the same in every iteration
Because it runs exactly $\log_2 n$ iterations
Every iteration without return shrinks $[left,right]$
Explanation. $left\le mid\le right$, and the new interval excludes $mid$: the quantity $right-left+1\ge 0$ strictly decreases, so eventually $left>right$. The number of iterations is at most $\lfloor\log_2 n\rfloor+1$, not exactly $\log_2 n$.
In BinarySearch ($mid=left+\lfloor(right-left)/2\rfloor$; if $a[mid]<m$ one sets $left=mid+1$) one writes by mistake $left=mid$. What can happen on $a=[1,3]$ searching for $m=3$?
It still returns $2$, the position of $3$
The loop does not terminate
It returns $-1$, because $3$ is discarded
It returns $1$, the last $mid$ examined
Explanation. $mid=1+\lfloor 1/2\rfloor=1$, $a[1]=1<3$, so $left=mid=1$: the state never changes. Correctness uses that the new interval excludes $mid$, so that it shrinks at every iteration.
Euclid's algorithm, while $m\ne 0$, replaces $(n,m)$ by $(m,\,n\bmod m)$ and then returns $n$. Why does it terminate on every pair of naturals?
Because $n$ decreases by exactly $1$ at each iteration
Because $\gcd(n,m)$ decreases at each iteration of the loop
Because $0\le n\bmod m<m$: $m$ strictly decreases
Because after two iterations $m$ is always $0$
Explanation. A strictly decreasing sequence of naturals cannot be infinite, so eventually $m=0$. The greatest common divisor instead stays constant: it is the invariant used for correctness.
Euclid's algorithm maintains the invariant $\gcd(n,m)=\gcd(n_0,m_0)$, where $(n_0,m_0)$ is the input, and exits when $m=0$ returning $n$. Which fact closes the correctness proof?
$\gcd(n,0)=n$
$\gcd(n,0)=0$
$\gcd(n,m)=\gcd(m,n)$
$n\bmod m<m$
Explanation. At exit the invariant says $\gcd(n_0,m_0)=\gcd(n,0)$, and every $d$ divides $0$, so the greatest common divisor of $n$ and $0$ is $n$. $n\bmod m<m$ serves instead for termination.
RecursiveSum$(a,n)$ returns $a[1]$ if $n=1$, otherwise RecursiveSum$(a,n-1)+a[n]$. One proves by induction on $n$ that it returns $a[1]+\dots+a[n]$. What is checked in the base case?
That for $n=0$ it returns $0$, the empty sum
That the call on $n-1$ is correct
That for $n=1$ it returns $a[1]$
That the recursion makes exactly $n$ calls
Explanation. The base case of the induction matches the base case of the algorithm, $n=1$. Correctness of the call on $n-1$ is the inductive hypothesis, used in the inductive step.
In the inductive proof of correctness of a recursive algorithm, why is it essential that every recursive call receives a smaller instance?
To apply the inductive hypothesis, and to terminate
Because small instances need less memory
Because the algorithm must have a single base case
Because otherwise the running time would not be polynomial
Explanation. The inductive hypothesis covers instances of smaller size; on an instance of the same size it says nothing, and the recursion might never reach the base case.
For a loop one proves that an invariant holds at the start and is maintained by every iteration, but not that the loop terminates. What can be concluded about the output?
That the output is correct
Nothing: without termination there is no output
That the output is correct in the worst case
That the loop runs $n$ iterations
Explanation. Initialisation and maintenance give only «if the loop ends, then the invariant holds». Termination is the third property, and it is needed to conclude.
The function WrongFactorial$(n)$ returns $n\cdot$WrongFactorial$(n-1)$ without any base case. What happens when calling WrongFactorial$(2)$?
It returns $2$: the recursion stops by itself at $n=1$, because $1\cdot$WrongFactorial$(0)$ is $1$.
The recursion does not terminate: the calls continue on $1,0,-1,\dots$ until the memory reserved to the calls is exhausted (stack overflow).
It returns $0$: the call on $n=0$ multiplies the result by $0$ and the recursion stops.
It returns $2$, because the recursion stops at $n=0$ with value $1$.
Explanation. Without a base case the chain of calls never stops; in practice the computer stops it with a stack overflow error. Multiplying by $0$ does not help: the product is computed only when the calls return.
Factorial$(n)$ returns $1$ if $n=0$, otherwise $n\cdot$Factorial$(n-1)$. The recursion depth is the maximum number of calls active at the same time. What is it for Factorial$(n)$?
$n$
$\lfloor\log_2 n\rfloor+1$
$2n+2$
$n+1$
Explanation. The calls with inputs $n,n-1,\dots,0$ are all simultaneously active in the call stack: $n+1$ stack frames, hence $\Theta(n)$ memory. $2n+2$ is the number of steps.
An algorithm is tail recursive if the recursive call is the last operation and its result is returned unchanged. RecursiveGCD$(n,m)$ returns $n$ if $m=0$, otherwise RecursiveGCD$(m,n\bmod m)$; Factorial$(n)$ returns $n\cdot$Factorial$(n-1)$; Fib$(n)$ returns Fib$(n-1)+$Fib$(n-2)$; Hanoi makes a call, a move and another call. Which one is tail recursive?
Factorial
Fib
RecursiveGCD
Hanoi
Explanation. RecursiveGCD returns unchanged the result of RecursiveGCD$(m,n\bmod m)$: the call is the last operation. Factorial multiplies the result by $n$, Fib adds two calls, Hanoi performs a move and another call after the first one.
Fib$(n)$ returns $n$ if $n\le 1$, otherwise Fib$(n-1)+$Fib$(n-2)$. How many calls in total does Fib$(4)$ execute, and what is the recursion depth (maximum number of calls active together)?
$9$ calls, depth $4$
$9$ calls, depth $5$
$5$ calls, depth $4$
$8$ calls, depth $3$
Explanation. The calls satisfy $C(n)=C(n-1)+C(n-2)+1$, with $C(0)=C(1)=1$: $C(4)=9$; the longest path is Fib$(4)\to$Fib$(3)\to$Fib$(2)\to$Fib$(1)$, with $4$ nodes. The number of steps depends on the nodes, the stack memory on the depth.
Counting one step per executed line, FastPower satisfies $S(0)=2$ and $S(n)=S(\lfloor n/2\rfloor)+4$ for $n\ge 1$. What is $S(13)$?
$16$
$18$
$14$
$54$
Explanation. The exponents are $13,6,3,1,0$: four calls with $n\ge 1$ of $4$ steps plus the base case of $2$, i.e., $4(\lfloor\log_2 13\rfloor+1)+2=4\lfloor\log_2 n\rfloor+6=18$.
A recursive algorithm receives inputs with a size in $\N$; on the base cases it returns the correct output. Which further assumption guarantees that it terminates and is correct on every input?
None: if the output is correct on the base cases, by induction the algorithm is correct on every input.
Every call is on an input of smaller or equal size, and the output is correct whenever the calls' outputs are.
The algorithm terminates on every input: then it returns the correct output, since the base cases do.
Every other input makes finitely many calls, on strictly smaller sizes, and combines their outputs correctly.
Explanation. Both assumptions are needed; the size must decrease strictly, otherwise the call on an input of size $n$ may repeat forever.
A recursive algorithm is correct on the base cases and, on an input of size $n$, calls itself on sizes smaller than $n$ (not necessarily $n-1$) and combines their outputs. With which technique do we prove that it is correct on every input?
With a loop invariant, proving initialization, maintenance and termination.
By strong induction on the size $n$ of the input: the statement is assumed for all sizes $k<n$.
By induction on the number of base cases.
By simple induction, assuming the statement only for size $n-1$.
Explanation. The recursive calls may be on any size smaller than $n$ (for instance $\lfloor n/2\rfloor$), so the inductive hypothesis on all sizes $k<n$ is needed: this is strong induction.
FastPower$(x,n)$ returns $1$ if $n=0$; otherwise it computes $y=$FastPower$(x,\lfloor n/2\rfloor)$ and returns $y\cdot y$ ($n$ even) or $x\cdot y\cdot y$ ($n$ odd). Why does the proof that it returns $x^n$ use strong induction?
Because the algorithm has two base cases, $n=0$ and $n=1$, to be handled together.
Because the algorithm makes two recursive calls, one for each half of the exponent.
It is not needed: simple induction from $n-1$ to $n$ is enough.
Because the inductive hypothesis is used for the exponent $\lfloor n/2\rfloor$, not for $n-1$.
Explanation. The call is FastPower$(x,\lfloor n/2\rfloor)$ and $\lfloor n/2\rfloor<n$, but in general $\lfloor n/2\rfloor\ne n-1$. FastPower has a single base case ($n=0$) and a single recursive call.
Towers of Hanoi: move $n\ge 1$ disks from one peg to another, one at a time, never a disk on a smaller one. $M(n)$ are the moves of the recursive algorithm Hanoi, $M^*(n)$ the minimum over all algorithms. Which statement is correct?
Hanoi performs $M(n)=2^n-1$ moves, and no algorithm can use fewer: $M^*(n)=2^n-1$.
Hanoi performs $2^n-1$ moves, but there are algorithms using $\bigO(n^2)$.
Hanoi performs $n^2$ moves, and this number is optimal.
Hanoi performs $2^{n-1}$ moves, since every disk moves only once.
Explanation. Observations 14.14 and 14.15: $M(n)=2M(n-1)+1$ gives $2^n-1$, and every algorithm must move the tower of the $n-1$ smaller disks twice, before and after the move of the largest disk.
Towers of Hanoi with $n$ disks: $M^*(n)$ is the minimum number of moves over all algorithms (one disk at a time, never on a smaller one). Which argument is the proof that $M^*(n)\ge 2^n-1$ based on?
Every disk must move at least once, and disk $k$ at least $2^{k-1}$ times by induction on $k$.
The algorithm Hanoi uses exactly $2^n-1$ moves, hence no algorithm can use fewer.
Before and after the move of the largest disk, the other $n-1$ form a tower on another peg: $M^*(n)\ge 2M^*(n-1)+1$.
The moves satisfy $M(n)=M(n-1)+M(n-2)+1$, like the calls of Fib, which grow as $2^n$.
Explanation. The existence of an algorithm with $2^n-1$ moves only gives $M^*(n)\le 2^n-1$; the lower bound requires the argument on the largest disk. «At least $n$ moves» is true but too weak.
Factorial$(n)$ returns $1$ if $n=0$, otherwise $n\cdot$Factorial$(n-1)$. How does one prove that Factorial$(n)$ terminates and returns $n!$ for every $n\in\N$?
By induction on $n$: for $n=0$ it returns $1=0!$; if Factorial$(n-1)$ returns $(n-1)!$, then $n\cdot(n-1)!=n!$.
With a loop invariant, proving initialization, maintenance and termination on the loop of the calls.
By strong induction on the exponent $\lfloor n/2\rfloor$, as for FastPower, with the two cases $n$ even and $n$ odd.
By checking the result for $n=0,1,\dots,5$: the algorithm is the same for every $n$, so one generic case suffices.
Explanation. The only recursive call is on $n-1$, so simple induction suffices: base case $n=0$, inductive step from the hypothesis on $n-1$. Examples can show that an algorithm is wrong, not that it is correct.
Counting one step per executed line, Factorial (test «$n=0$?», then «return $1$» or «return $n\cdot$Factorial$(n-1)$») satisfies $S(0)=2$ and $S(n)=S(n-1)+2$ for $n\ge 1$. Which closed form does the expansion method give?
$S(n)=2n$
$S(n)=2^{n+1}$
$S(n)=2n+2$
$S(n)=n+2$
Explanation. Expanding $k$ times gives $S(n)=S(n-k)+2k$; with $k=n$ the base case is reached: $S(n)=S(0)+2n=2n+2=\Theta(n)$.
Fib$(n)$ returns $n$ if $n\le 1$, otherwise Fib$(n-1)+$Fib$(n-2)$. Let $F(n)$ be the Fibonacci numbers ($F(0)=0$, $F(1)=1$) and $C(n)$ the number of calls executed by Fib$(n)$, including the first one. Which statement is correct?
$C(n)=2F(n+1)-1$ for every $n\in\N$
$C(n)=F(n+1)$ for every $n\in\N$
$C(n)=2F(n)-1$ for every $n\ge 1$
$C(n)=n+1$ for every $n\in\N$
Explanation. $C(0)=C(1)=1$ and $C(n)=C(n-1)+C(n-2)+1$; by strong induction $C(n)=2F(n+1)-1$ (for instance $C(5)=2\cdot 8-1=15$). $n+1$ would be the number of distinct subproblems.
The number of calls of Fib$(n)$ satisfies $C(0)=C(1)=1$ and $C(n)=C(n-1)+C(n-2)+1$ for $n\ge 2$. On which step is the inductive step of the proof of $C(n)\ge 2^{n/2}$ based?
$C(n)\ge C(n-1)+1$; repeating it $n$ times gives $C(n)\ge n$, which is larger than $2^{n/2}$ for every $n$.
$C(n)\ge 2\,C(n-1)$, because the two calls have the same number of descendants; hence $C(n)\ge 2^n$.
$C(n)\ge 2\,C(n-2)$, because $C(n-1)\ge C(n-2)$; with the inductive hypothesis $C(n)\ge 2\cdot 2^{(n-2)/2}=2^{n/2}$.
The Master Theorem applied to $C(n)=2\,C(n/2)+1$, which gives $\Theta(n)$ calls and hence the bound.
Explanation. Strong induction with two base cases suffices ($C(2)=3\ge 2$, $C(3)=5\ge 2^{3/2}$). $C(n-1)$ and $C(n-2)$ are not equal, so $C(n)\ge 2C(n-1)$ is false; the recurrence is not in standard form.
RecursiveGCD$(n,m)$ returns $n$ if $m=0$, otherwise RecursiveGCD$(m,\,n\bmod m)$. Let $m_0=m,m_1,m_2,\dots$ be the second arguments of the successive calls; one proves that $m_{k+2}<m_k/2$. Which consequence follows?
The number of calls is at most $m$, because the second argument decreases by at least $1$.
The number of calls is $\Theta(\sqrt m)$, like the trial divisions of the primality test.
The number of calls is at most $2$, because the second argument halves every two calls.
The number of calls is at most $2\lfloor\log_2 m\rfloor+3$, i.e., $\bigO(\log_2 m)$.
Explanation. Every two calls the second argument is at least halved, so after about $2\log_2 m$ calls it becomes $0$. The bound «at most $m_0$» suffices for termination, but it is very pessimistic.
Hanoi$(n)$ moves $n\ge 1$ disks: if $n=1$ it makes one move; otherwise it calls Hanoi$(n-1)$, moves the largest disk and calls Hanoi$(n-1)$ again. How many calls does it execute in total, including the first one, and what is the depth of the recursion (maximum number of calls active at the same time)?
$2^n-1$ calls, depth $2^n-1$
$2^n-1$ calls, depth $n$
$n$ calls, depth $n$
$2^n-1$ calls, depth $\lfloor\log_2 n\rfloor+1$
Explanation. The calls satisfy $C(1)=1$, $C(n)=2C(n-1)+1$, hence $C(n)=2^n-1$; but at any moment only the calls on $n,n-1,\dots$ along one path of the tree are active: the depth is $n$.
Among Factorial$(n)$ (one call on $n-1$), Fib$(n)$ (calls on $n-1$ and $n-2$), FastPower$(x,n)$ (one call on $\lfloor n/2\rfloor$) and Hanoi$(n)$ (two calls on $n-1$), which one performs $\Theta(\log_2 n)$ steps, and with which depth of the recursion?
FastPower, with depth $\lfloor\log_2 n\rfloor+2$
Factorial, with depth $n+1$
Hanoi, with depth $n$
Fib, with depth $n$
Explanation. FastPower halves the exponent with constant work: $S(n)=S(\lfloor n/2\rfloor)+4$, i.e., $4\lfloor\log_2 n\rfloor+6$ steps, with one call per level down to $n=0$. Factorial is $\Theta(n)$, Fib and Hanoi are exponential.
Fib$(n)$ returns $n$ if $n \le 1$, otherwise Fib$(n-1)+$Fib$(n-2)$. To prove that it returns the Fibonacci number $F(n)$, which form of induction is needed?
Simple induction with the single base case $n=0$
A loop invariant
None: checking $n=0,\dots,5$ suffices
Strong induction, with base cases $n=0$ and $n=1$
Explanation. The inductive step uses correctness for $n-1$ and $n-2$; so two base cases are needed. With the single case $n=0$, $n=1$ would not be covered.
RecursiveGCD$(n,m)$ returns $n$ if $m=0$, otherwise RecursiveGCD$(m,n \bmod m)$. Which two facts prove that it terminates and returns $\gcd(n,m)$?
$\gcd(n,m)=\gcd(n-1,m)$, and the first argument decreases
$\gcd(n,m)=\gcd(m,n \bmod m)$, and the second argument strictly decreases ($n \bmod m<m$) down to $0$
$n$ and $m$ are coprime
The recursion is tail recursion
Explanation. Euclid's property preserves the result and $0 \le n \bmod m<m$ guarantees termination; with $m=0$, $\gcd(n,0)=n$. Tail recursion concerns memory, not correctness.
Hanoi$(n,from,to,aux)$ moves $n-1$ disks to $aux$, disk $n$ to $to$, then the $n-1$ disks to $to$. In the induction proof, why do the calls on $n-1$ disks never break the rule «never a larger disk on a smaller one»?
Because disks are moved two at a time
Because peg $aux$ is always empty
Because disk $n$ is larger than the moved ones
Because $n$ is even
Explanation. The statement includes the hypothesis on the disks below: while the $n-1$ disks move, disk $n$ and those under it are larger, so they do no harm. $aux$ is not necessarily empty.
A recursive algorithm solves an instance by calling itself on smaller instances, down to a base case. Which function, defined on the naturals, terminates for every $n\ge 0$?
$G(n)$: return $G(n-1)+2$, with no base case
$H(n)$: if $n=0$ return $0$, otherwise $H(n+1)-2$
$K(n)$: if $n=0$ return $0$, otherwise $K(n)+2$
$F(n)$: if $n=0$ return $0$, otherwise $F(n-1)+2$
Explanation. Only $F$ calls itself on a strictly smaller argument that reaches the base case. $G$ has no base case, $H$ moves away from $0$, $K$ calls the same instance again.
Mystery$(n)$, with $n$ an integer, returns $0$ if $n=0$, otherwise Mystery$(n-2)+1$. For which $n\ge 0$ does the recursion terminate?
Only for even $n$
For every $n\ge 0$
Only for odd $n$
For no $n\ge 1$
Explanation. From an even $n$ one goes down by $2$ until $0$. From an odd $n$ one passes $1$ and then $-1,-3,\dots$ never meeting the base case: the size must decrease towards a base case, not merely decrease.
Hanoi$(n)$, with base case $n=1$, calls Hanoi$(n-1)$ twice for $n>1$. In the recursive call tree of Hanoi$(4)$, how many nodes and how many leaves are there?
$16$ nodes and $8$ leaves
$15$ nodes and $4$ leaves
$15$ nodes and $8$ leaves
$8$ nodes and $4$ leaves
Explanation. Level $j$ has $2^j$ nodes, for $j=0,\dots,3$: $1+2+4+8=15$ nodes; the leaves are the $8$ calls Hanoi$(1)$ on the last level.
FastPower$(x,n)$ returns $1$ if $n=0$, otherwise it calls FastPower$(x,\lfloor n/2\rfloor)$ once. Each active call takes one stack frame. What is the largest number of frames in the call stack during FastPower$(x,1000)$?
$11$
$10$
$1000$
$500$
Explanation. The exponents are $1000,500,250,125,62,31,15,7,3,1,0$: $11$ nested calls, all active together when the base case is reached. The largest number of frames is the recursion depth.
Correctness of an iterative algorithm is proved with a loop invariant (initialisation, maintenance, termination), that of a recursive algorithm by induction. What does maintenance of the invariant correspond to?
To the base case (or cases) of the recursion
To the size decreasing down to a base case
To the inductive step of the proof
To the number of recursive calls made
Explanation. Initialisation ↔ base cases; maintenance ↔ inductive step; loop termination ↔ size strictly decreasing towards a base case.
An iterative and a recursive algorithm solve the same problem. Which statement describes the difference in «direction» between the two correctness proofs?
The iterative one goes from the original instance, the recursive one bottom-up
The iterative one goes bottom-up, the recursive one from the original instance
Both start from the base cases and go up to the original instance
Only the iterative one needs a proof of termination
Explanation. The loop proceeds from initialisation to the last iteration; recursion reduces the original instance to smaller ones. Both must terminate: recursion needs the size to decrease towards a base case.
Factorial$(n)$ returns $1$ if $n=0$, otherwise $n\cdot$Factorial$(n-1)$. A variant uses $n=1$ as its only base case (it returns $1$ if $n=1$). What happens calling the variant with $n=0$?
It returns $1$, that is the value of $0!$
It returns $0$, because it multiplies by $n=0$
It returns $1$ after a single call
The recursion never ends
Explanation. With $n=0$ the test $n=1$ fails and $0\cdot$Factorial$(-1)$ is computed, and so on: the base case is never reached. The inductive proof must cover every allowed instance with the base cases.
Factorial$(n)$ (base case $n=0$, call on $n-1$) has recursion depth $n+1$; each stack frame takes constant memory. How much memory does its call stack use, and how much does a loop computing $n!$ with an accumulator use?
$\Theta(1)$ and $\Theta(1)$
$\Theta(n)$ and $\Theta(n)$
$\Theta(\log n)$ and $\Theta(1)$
$\Theta(n)$ and $\Theta(1)$
Explanation. The calls on $n,n-1,\dots,0$ are all on the stack together, hence $\Theta(n)$ frames. The loop uses a fixed number of variables. The steps are $\Theta(n)$ in both cases.
IterativeFib$(n)$ sets $prev:=0$, $curr:=1$, $i:=2$ and, while $i\le n$, runs $next:=prev+curr$, $prev\leftarrow curr$, $curr\leftarrow next$, $i\leftarrow i+1$. The invariant is $prev=F(i-2)$, $curr=F(i-1)$ ($F$: Fibonacci numbers, $F(0)=0$, $F(1)=1$). With $n=7$, what are $prev$ and $curr$ when the condition is checked with $i=6$?
$prev=5$, $curr=8$
$prev=2$, $curr=3$
$prev=3$, $curr=5$
$prev=5$, $curr=3$
Explanation. By the invariant $prev=F(4)=3$ and $curr=F(5)=5$. At the end $i=8$ and $curr=F(7)=13$.
The naive recursive version Fib performs $4F(n+1)-2$ steps, IterativeFib $5n+1$ steps ($F$: Fibonacci numbers, $F(21)=10946$). How many steps does each perform with $n=20$?
$43782$ and $101$
$101$ and $101$
$43782$ and $43782$
$400$ and $101$
Explanation. $4\cdot 10946-2=43782$ against $5\cdot 20+1=101$. Fib recomputes the same subproblems many times; IterativeFib computes each $F(i)$ only once.
RecursiveGCD$(n,m)$ returns $n$ if $m=0$, otherwise RecursiveGCD$(m,\,n\bmod m)$. How many calls in all does RecursiveGCD$(84,36)$ make, and what does it return?
$2$ calls, returns $12$
$3$ calls, returns $12$
$3$ calls, returns $36$
$4$ calls, returns $6$
Explanation. $(84,36)\to(36,12)\to(12,0)$: the third call is the base case and returns $12=\gcd(84,36)$, which goes back unchanged to the first.
An algorithm is tail recursive if every recursive call is the last operation and its result is returned unchanged (like RecursiveGCD). How can a tail-recursive algorithm always be transformed?
Into two recursive calls on half of the input
Into an algorithm without a base case
Into a for loop with an array of $n$ frames
Into a while loop that updates the parameters
Explanation. The tail call has nothing to do after returning, so it can be replaced by updating the parameters and repeating until the base case: RecursiveGCD becomes the iterative Euclidean algorithm.
RecursiveGCD$(n,m)$ (returns $n$ if $m=0$, otherwise RecursiveGCD$(m,\,n\bmod m)$) performs $2$ steps per call. How many calls and steps does it perform with $(n,m)=(89,55)$, two consecutive Fibonacci numbers?
$9$ calls and $18$ steps
$10$ calls and $20$ steps
$10$ calls and $10$ steps
$55$ calls and $110$ steps
Explanation. The remainders run through the Fibonacci numbers: $(89,55),(55,34),(34,21),(21,13),(13,8),(8,5),(5,3),(3,2),(2,1),(1,0)$, that is $10$ calls. It is the worst case: still, the second argument halves at least every two calls.
FastPower$(x,n)$ returns $1$ if $n=0$; otherwise it computes $y=$FastPower$(x,\lfloor n/2\rfloor)$ and returns $y\cdot y$ if $n$ is even, $y\cdot y\cdot x$ if $n$ is odd. Why is the extra factor $x$ needed in the odd case?
Because $\lfloor n/2\rfloor=n/2$ also for odd $n$
Because the base case returns $x$ instead of $1$
Because $y=x^{n+1}$ when $n$ is odd
Because $2\lfloor n/2\rfloor=n-1$, so $y\cdot y=x^{n-1}$
Explanation. By the inductive hypothesis $y=x^{\lfloor n/2\rfloor}$. If $n$ is odd, $\lfloor n/2\rfloor=(n-1)/2$ and $y^2=x^{n-1}$: multiplying by $x$ gives $x^n$.
FastPower$(x,n)$ performs $\Theta(\log n)$ steps, the repeated product $x\cdot x\cdots x$ performs $\Theta(n)$. The input is the natural $n$, with $|I|=\Theta(\log n)$. How do the two running times (FastPower, then repeated product) grow as functions of $|I|$?
$\Theta(|I|)$ and $2^{\Theta(|I|)}$
$\Theta(|I|)$ and $\Theta(|I|)$
$2^{\Theta(|I|)}$ and $2^{\Theta(|I|)}$
$\Theta(\log|I|)$ and $\Theta(|I|)$
Explanation. $\log n=\Theta(|I|)$, while $n=2^{\Theta(|I|)}$. Halving the exponent makes the algorithm polynomial (linear) in the input size; the repeated product is exponential.
Hanoi with $n$ disks makes $M(n)=2^n-1$ moves. With $n=64$ disks and one move per second (a year has about $3.15\cdot 10^7$ seconds, and $2^{64}\approx 1.8\cdot 10^{19}$), how long does it take?
About $64$ seconds
About $68$ minutes
About $5.8\cdot 10^{11}$ years
About $1.8\cdot 10^{19}$ years
Explanation. $1.8\cdot 10^{19}/3.15\cdot 10^7\approx 5.8\cdot 10^{11}$ years. $1.8\cdot 10^{19}$ is the number of seconds, not years; $64$ and $4096$ seconds ($68$ minutes) would be $n$ and $n^2$ moves.
A recursive algorithm performs a constant number of steps per call and uses stack frames of constant size. What do the total number of steps and the memory used by the call stack depend on?
Both on the depth of the tree
Both on the number of nodes of the tree
Steps on the tree's nodes; memory on its depth
Steps on the depth; memory on the nodes
Explanation. Each call is a node and costs a fixed number of steps; at any time the stack holds only the calls on one path from the root. Fib$(4)$: $9$ calls, but at most $4$ frames together.
$G(n)$ returns $1$ if $n=0$, otherwise $G(n-1)+G(n-1)$ (two identical calls). How many calls in all does $G(5)$ make, and what is the recursion depth?
$63$ calls, depth $6$
$6$ calls, depth $6$
$32$ calls, depth $5$
$63$ calls, depth $63$
Explanation. The tree is a complete binary tree with levels $0,\dots,5$: $2^6-1=63$ nodes, but a root-to-leaf path holds only $6$. Writing $2\cdot G(n-1)$ would give $6$ calls.
Fib$(n)$ returns $n$ if $n\le 1$, otherwise Fib$(n-1)+$Fib$(n-2)$. While computing Fib$(6)$, how many times is Fib$(2)$ called?
$3$
$8$
$1$
$5$
Explanation. The calls with argument $k\ge 1$ in Fib$(n)$ are $F(n-k+1)$: for $k=2$, $F(5)=5$. The same subproblem is solved many times: this is the cause of the exponential number of calls.
In RecursiveGCD$(n,m)$ (call on $(m,\,n\bmod m)$) the second argument halves at least every two calls. Why can one not say «at every call»?
Because $n\bmod m$ can exceed $m$
Because the second argument can stay the same
Because $n\bmod m$ can be close to $m$, as in $(13,8)\to(8,5)$
One can: it always halves at every call
Explanation. $5>8/2$: in one call the remainder may drop only a little. In the next one, however, $8\bmod 5=3$ and $3\le 8/2$: two calls always suffice to halve it.
The recurrence $S(n)=2\,S(n/2)+c$ of RecursiveSum is in standard form $T(n)=a\,T(n/b)+f(n)$. What do $a$, $b$ and $f(n)$ represent?
$a=2$ subproblems, each of size $n/b=n/2$; $f(n)=c$ is the cost to divide and combine.
$a=2$ is the size of each subproblem, $b=2$ the number of subproblems.
$a=2$ and $b=2$ are the number of base cases; $f(n)=c$ is the cost of the base cases.
$f(n)=c$ is the total cost of the leaves of the recursion tree.
Explanation. Definition 15.2: $a\ge 1$ is the number of subproblems, $n/b$ (with $b>1$) the size of each of them, $f(n)$ the work to divide the problem and combine the solutions.
Explanation. We have $a^{\log_b n}=n^{\log_b a}$ (Observation 15.3): this is the identity relating the number of leaves $a^{\log_b n}$ of the recursion tree to $n^{\log_b a}$.
With the expansion method, what is the solution of $T(n)=T(n-1)+n$ with $T(1)=1$?
$T(n)=n=\Theta(n)$
$T(n)=\frac{n(n+1)}{2}=\Theta(n^2)$
$T(n)=n\log_2 n$
$T(n)=2^n-1$
Explanation. Expanding, $T(n)=n+(n-1)+\dots+2+T(1)=\sum_{i=1}^n i=\frac{n(n+1)}{2}$. The recurrence is not in standard form: the subproblem has size $n-1$.
Explanation. Level $j$ has $3^j$ nodes of size $n/4^j$, each of cost $c\,(n/4^j)^2$: $(3/16)^j c\,n^2$ in total. The geometric series with ratio $3/16<1$ is bounded, and the root dominates.
Let $T(1)=1$ and $T(n)=2T(\lfloor n/2\rfloor)+1$ for $n>1$. Which statement is correct?
$n\le T(n)\le 2n-1$ for all $n\ge 1$, hence $T(n)=\Theta(n)$.
$T(n)\le n$ for all $n\ge 1$.
$T(n)=\Theta(n\log n)$, as for $2T(\lfloor n/2\rfloor)+n$.
$T(n)\le c\,n$ cannot be proved for any constant $c$, hence $T(n)\ne\bigO(n)$.
Explanation. This is Observation 15.6. For $n$ a power of $2$ we have $T(n)=2n-1>n$. The guess $T(n)\le c\,n$ makes the inductive step fail because of the term $+1$, but $T(n)=\bigO(n)$ is true: it is enough to strengthen the guess.
With the substitution method we want to prove $T(n)=\bigO(n)$ for $T(1)=1$, $T(n)=2T(\lfloor n/2\rfloor)+1$. Which inductive hypothesis makes the inductive step work?
$T(k)\le c\,k$ for all $k<n$, with $c$ large enough.
$T(k)\le k$ for all $k<n$.
$T(k)\le c\,k-d$ for all $k<n$, with $d\ge 1$ (for instance $c=2$, $d=1$).
$T(k)\le c\,k^2$ for all $k<n$, which gives $T(n)=\bigO(n)$.
Explanation. With $T(k)\le c\,k$ one only gets $T(n)\le c\,n+1$; subtracting a lower-order term, $T(n)\le 2(c\lfloor n/2\rfloor-d)+1\le c\,n-2d+1\le c\,n-d$ if $d\ge 1$. A guess $c\,k^2$ would only give $\bigO(n^2)$.
To solve $T(n)=2T(\lfloor\sqrt n\rfloor)+\log_2 n$ we set $m=\log_2 n$ and $R(m)=T(2^m)$. Which recurrence do we obtain, and what is the order of growth of $T(n)$?
Explanation. $\sqrt n=2^{m/2}$, hence $T(2^m)=2T(2^{m/2})+m$, i.e., $R(m)=2R(m/2)+m$, whose solution is $\Theta(m\log m)$; going back to $n$ we get $\Theta(\log_2 n\cdot\log_2\log_2 n)$.
With the expansion method (substituting the recurrence into itself down to the base case), what is the solution of $T(n)=2T(n-1)+1$ with $T(0)=0$?
$T(n)=2^n$
$T(n)=n\,2^{n-1}$
$T(n)=2^n-1$
$T(n)=2n-1$
Explanation. After $k$ substitutions $T(n)=2^kT(n-k)+(2^{k-1}+\dots+2+1)=2^kT(n-k)+2^k-1$; with $k=n$ one gets $T(n)=2^n\cdot 0+2^n-1$. It is the number of moves of the Towers of Hanoi.
In the recursion tree of $T(n)=a\,T(n/b)+f(n)$ ($a\ge 1$, $b>1$ constants, $n$ exact power of $b$, $T(1)=\Theta(1)$), how many leaves are there and what is the cost of the level at depth $j$?
Explanation. At depth $j$ there are $a^j$ nodes of size $n/b^j$; the size reaches $1$ at depth $\log_b n$, so the leaves are $a^{\log_b n}=n^{\log_b a}$. The leaves are $n$ only when $a=b$.
In the recursion tree of $T(n)=8\,T(n/2)+n^2$ ($n$ power of $2$, $T(1)=\Theta(1)$), how do the level costs evolve and what is the order of growth of $T(n)$?
They decrease going down (the root dominates): $T(n)=\Theta(n^2)$
They are all equal: $T(n)=\Theta(n^2\log n)$
They increase going down (the leaves dominate): $T(n)=\Theta(n^3)$
They increase going down (the leaves dominate): $T(n)=\Theta(n^3\log n)$
Explanation. Level $j$ costs $8^j(n/2^j)^2=2^j\,n^2$: the costs grow geometrically and the total is dominated by the $n^{\log_2 8}=n^3$ leaves. The factor $\log n$ appears only when the levels have equal cost.
Which method is the most suitable to obtain the order of growth of $T(n)=T(n/3)+T(2n/3)+c\,n$?
The Master Theorem with $a=2$ and $b=3/2$, because the largest subproblem has size $2n/3$.
The recursion tree: the two branches have different lengths and each level costs at most $c\,n$.
The expansion method, which always gives an exact closed form for recurrences of this type.
None: a recurrence with two different recursive terms cannot be solved.
Explanation. The recurrence is not in standard form ($a\,T(n/b)$ with a single size $n/b$), so the Master Theorem does not apply. The (unbalanced) tree has depth $\Theta(\log n)$ and suggests $\Theta(n\log n)$, to be confirmed by substitution.
For $T(1)=1$ and $T(n)=2T(\lfloor n/2\rfloor)+n$ one already expects the solution $\Theta(n\log n)$, and wants a rigorous proof, with the floors and the boundary condition. Which method is used?
The recursion tree, which with floors directly gives a complete proof.
The expansion method, ignoring the floors: the result then holds for every $n$.
The Master Theorem, which holds only for $n$ exact power of $2$ and therefore suffices.
The substitution method, proving $\bigO$ and $\Omega$ separately by induction.
Explanation. Substitution verifies a guess that is already known, handling floors and base cases through the choice of the threshold. The tree and the expansion mainly serve to obtain the guess.
A recurrence equation describes a function $T:\N \to \R$ through its values on smaller inputs. Why are initial conditions also needed?
Because the recurrence holds only for even $n$
Because the initial conditions give the order of growth
Because without the values of the base cases the recurrence does not determine a unique function
They are not needed
Explanation. $T(n)=2T(n-1)$ is satisfied by $c\,2^n$ for every $c$: the base case fixes $c$. The order of growth, instead, often does not depend on the base cases.
For $T(n)=2T(\lfloor n/2\rfloor)+n$ one proves $T(n) \le 2n\log_2 n$ for $n \ge 2$ by the substitution method. In the inductive step, which fact about the logarithm is used?
$\log_2\lfloor n/2\rfloor \le \log_2 n-1$
$\log_2 n \le n$
$\log_2(n/2)=\log_2 n$
$\lfloor n/2\rfloor \ge n/2$
Explanation. $2T(\lfloor n/2\rfloor)+n \le 2\cdot 2\lfloor n/2\rfloor(\log_2 n-1)+n \le 2n\log_2 n-2n+n \le 2n\log_2 n$. Without the $-1$ the $+n$ term would stay uncovered.
For $T(n)=2T(\lfloor n/2\rfloor)+n$ (with a base case) one proves $T(n) \le 2n\log_2 n$ for $n \ge 2$ and $T(n) \ge \frac14 n\log_2 n$ for $n \ge 1$. What is concluded?
$T(n)=\Theta(n)$
$T(n)=\Theta(n\log_2 n)$
$T(n)=O(n\log_2 n)$ but not $\Omega(n\log_2 n)$
$T(n)=\Theta(n^2)$
Explanation. An upper and a lower bound of the same order give $\Theta$; the constants $2$ and $1/4$ are irrelevant. It is the recurrence of Merge Sort.
A recursive algorithm, on an input of size $n>1$, performs a constant number $c$ of steps plus two recursive calls, each on half of the input. Which recurrence describes its number of steps $S(n)$?
$S(n)=S(n/2)+2c$
$S(n)=2S(n-1)+c$
$S(n)=2S(n/2)+c$
$S(n)=S(n-2)+c$
Explanation. Two subproblems ($a=2$) of size $n/2$ ($b=2$), with constant work to divide and combine. $2S(n-1)+c$ is Hanoi's form, with subproblems of size $n-1$.
A recurrence is in standard form if it is written $T(n)=a\,T(n/b)+f(n)$ with constants $a\ge 1$ and $b>1$. Which of the following is NOT in standard form?
$T(n)=T(n/2)+1$
$T(n)=3T(n/4)+n^2$
$T(n)=7T(n/2)+n^2$
$T(n)=2T(n-1)+1$
Explanation. In $2T(n-1)+1$ the subproblem has size $n-1$, not a fraction $n/b$ of $n$ («decrease and conquer»). The others have $a=1,3,7$ and $b=2,4,2$.
The chapter on recurrences studies three solution methods: expansion, substitution, recursion tree. Which one requires the form of the solution to be known (or guessed) in advance?
The expansion method
The substitution method
The recursion-tree method
None of the three methods
Explanation. Substitution checks a proposed solution by induction, for instance $T(n)\le c\,n\log_2 n$. Expansion and the recursion tree serve instead to discover it.
The expansion method repeatedly substitutes the recurrence into itself. What does it give, for instance with $T(n)=T(n-1)+3$?
A hypothesis to be proved by induction
A recursion tree with two children per node
$T(n)=T(n-k)+3k$, down to the base case
Directly one of the three cases of the Master theorem
Explanation. After $k$ steps $T(n)=T(n-k)+3k$; with $k=n-1$ one reaches $T(1)$. The Master theorem does not apply: the recurrence is not in standard form.
When solving $T(n)=2T(n/2)+n$ one assumes that $n$ is an exact power of $2$, ignoring the floors and ceilings $\lfloor n/2\rfloor$ and $\lceil n/2\rceil$. Why is this usually legitimate?
Because floors normally do not change the order of growth
Because algorithm inputs always have a power-of-$2$ size
Because with floors the recurrence has no solution
Because floors and ceilings change only the base case
Explanation. It is a technical simplification: with $\lfloor n/2\rfloor$ the solution stays $\Theta(n\log n)$, as the substitution method confirms. Real inputs have arbitrary sizes.
For $T(n)=2T(n/2)+n$, with $n$ a power of $2$, the boundary condition is changed from $T(1)=1$ to $T(1)=5$. What happens to the solution?
It becomes $\Theta(5\,n\log n)$, a different order
It becomes $\Theta(n^5)$, because $T(1)=5$
It stays $\Theta(n\log n)$
It becomes $\Theta(n)$, because the base case dominates
Explanation. $T(n)=n\log_2 n+T(1)\,n$: the $n$ leaves cost $T(1)$ each, so $n\log_2 n+5n$. This is why one simply writes $T(1)=\Theta(1)$; and $\Theta(5\,n\log n)=\Theta(n\log n)$.
The geometric series $\sum_{j\ge 0} r^j$ equals $\frac{1}{1-r}$ for $0<r<1$. What is the largest possible value of $1+\frac34+\left(\frac34\right)^2+\dots+\left(\frac34\right)^k$, over all $k$?
$4$
$\frac34$
$\frac74$
It is unbounded
Explanation. $\frac{1}{1-3/4}=4$, and every partial sum is below the infinite sum. It is the computation showing that, in a recursion tree, levels with geometrically decreasing costs cost as much as the root up to a constant.
The number of iterations of a search that halves the interval satisfies $T(1)=1$ and $T(n)=T(n/2)+1$ ($n$ a power of $2$). Expanding the recurrence down to the base case, what is $T(n)$?
$T(n)=n$
$T(n)=\log_2 n$
$T(n)=n/2+1$
$T(n)=\log_2 n+1$
Explanation. $T(n)=T(n/2^k)+k$; with $k=\log_2 n$ one reaches $T(1)=1$, hence $\log_2 n+1$. It is the recurrence of BinarySearch.
One unrolls $T(n)=T(n/2)+n$, with $T(1)=1$ and $n$ a power of $2$: $T(n)=n+T(n/2)=n+\frac n2+T(n/4)=\dots$ What does one get on reaching the base case?
$T(n)=n\log_2 n+1$
$T(n)=2n-1$
$T(n)=n+\log_2 n$
$T(n)=n^2$
Explanation. $T(n)=n+\frac n2+\frac n4+\dots+2+T(1)=n+\frac n2+\dots+2+1=2n-1$: a geometric series, dominated by the first term. $n\log_2 n$ would come with two calls, $2T(n/2)+n$.
For $T(n)=2T(\lfloor n/2\rfloor)+n$ one wants $T(n)\le c\,n\log_2 n$ by the substitution method. From the inductive hypothesis $T(\lfloor n/2\rfloor)\le c\lfloor n/2\rfloor\log_2\lfloor n/2\rfloor$ one gets $T(n)\le c\,n\log_2(n/2)+n=c\,n\log_2 n-c\,n+n$. For which $c$ is the inductive step complete?
For every $c>0$
Only for $c\le 1$
For no $c$: a stronger hypothesis is needed
For every $c\ge 1$
Explanation. It suffices that $-c\,n+n\le 0$, that is $c\ge 1$. The base case then fixes the threshold on $n$ (for instance $n\ge 2$, because $\log_2 1=0$) and possibly a larger constant.
In the lower bound for $T(n)=2T(\lfloor n/2\rfloor)+n$ by the substitution method one needs an estimate of $\lfloor n/2\rfloor$ from below. Which inequality holds for every natural $n\ge 1$?
$\lfloor n/2\rfloor\ge n/2$
$\lfloor n/2\rfloor\ge (n-1)/2$
$\lfloor n/2\rfloor\le (n-1)/2$
$\lfloor n/2\rfloor\ge n-1$
Explanation. For even $n$, $\lfloor n/2\rfloor=n/2$, for odd $n$, $(n-1)/2$: in every case at least $(n-1)/2$. $\lfloor n/2\rfloor\ge n/2$ fails for odd $n$, and that is exactly the loss to be controlled in the proof.
To solve $T(n)=T(\sqrt n)+1$ one sets $m=\log_2 n$ and $R(m)=T(2^m)$, so that $T(\sqrt n)=R(m/2)$. What is the order of growth of $T(n)$?
$\Theta(\log\log n)$
$\Theta(\log n)$
$\Theta(\sqrt n)$
$\Theta(1)$
Explanation. $R(m)=R(m/2)+1$ gives $R(m)=\Theta(\log m)$, so $T(n)=\Theta(\log\log n)$: the square root halves the number of bits, and $\Theta(\log m)$ halvings are needed.
In the recursion tree of $T(n)=3T(n/4)+c\,n^2$, with $n$ a power of $4$ and $T(1)=\Theta(1)$, every internal node has $3$ children and the tree has $\log_4 n$ levels above the leaves. How many leaves are there?
$4^{\log_4 n}=n$
$3\cdot\log_4 n=\log_4 n^3$
$3^{\log_4 n}=n^{\log_4 3}$
$4^{\log_3 n}=n^{\log_3 4}$
Explanation. Level $j$ has $3^j$ nodes, and the leaves are at level $\log_4 n$. With the identity $a^{\log_b n}=n^{\log_b a}$ one gets $n^{\log_4 3}\approx n^{0.79}$, less than $n$.
In the recursion tree of $T(n)=3T(n/4)+c\,n^2$ level $j$ costs $\left(\frac{3}{16}\right)^j c\,n^2$. Why is $T(n)=\Theta(n^2)$?
Because the tree has $\Theta(n^2)$ levels of constant cost
Because every level costs $c\,n^2$
Because the leaves cost $\Theta(n^2)$ in all
Costs decrease geometrically: the root dominates
Explanation. $\sum_j(3/16)^j\le\frac{1}{1-3/16}=\frac{16}{13}$, so $T(n)\le\frac{16}{13}c\,n^2+\Theta(n^{\log_4 3})=\bigO(n^2)$, and the root alone gives $\Omega(n^2)$.
For $T(n)=2T(n/2)+c\,n$ with $T(1)=c$ and $n$ a power of $2$, the recursion tree has $\log_2 n$ internal levels costing $c\,n$ each and $n$ leaves. What is $T(n)$ exactly?
$c\,n\log_2 n$
$c\,n^2+c\,n$
$2c\,n\log_2 n$
$c\,n\log_2 n+c\,n$
Explanation. The internal levels cost $c\,n\log_2 n$ in all, the $n$ leaves $c\,n$. The order is $\Theta(n\log n)$; forgetting the leaves gives $c\,n\log_2 n$, which is right only asymptotically.
In the recursion tree of $T(n)=T(n/3)+T(2n/3)+c\,n$ the two children of a node of size $m$ have sizes $m/3$ and $2m/3$. How many levels does the longest root-to-leaf path have?
$\log_3 n$
$\log_{3/2} n$
$\log_2 n$
$n/3$
Explanation. The longest path always follows the $2n/3$ child: after $k$ steps the size is $(2/3)^k n$, which reaches $1$ for $k=\log_{3/2} n$. The shortest path, along the $n/3$ children, has $\log_3 n$ levels.
In the unbalanced tree of $T(n)=T(n/3)+T(2n/3)+c\,n$ every complete level costs $c\,n$, and the deepest levels are incomplete. How does one conclude that $T(n)=\Theta(n\log n)$?
By the Master theorem, case 2, as for $2T(n/2)+c\,n$
Because all paths have the same length
By counting levels: at most $\log_{3/2} n$, the first $\log_3 n$ complete
Because there are exactly $n$ leaves costing $c$ each
Explanation. Every level costs at most $c\,n$ and there are at most $\log_{3/2} n+1$ levels; down to depth $\log_3 n$ the tree is complete, and these levels alone cost $c\,n\log_3 n$. The Master theorem does not apply: the subproblems have different sizes.
In the recursion tree of $T(n)=4T(n/2)+n$, with $n$ a power of $2$, level $j$ has $4^j$ nodes of size $n/2^j$. How much does level $j$ cost (not counting the leaves)?
$2^j\,n$
$n$
$n/2^j$
$4^j\,n$
Explanation. $4^j\cdot\frac{n}{2^j}=2^j\,n$: costs grow by a factor $2$ at each level. $4^j n$ forgets that each node has size $n/2^j$.
In the recursion tree of $T(n)=4T(n/2)+n$ ($n$ a power of $2$, $T(1)=\Theta(1)$) level costs grow geometrically and there are $4^{\log_2 n}$ leaves. What is the order of growth of $T(n)$?
$\Theta(n\log n)$
$\Theta(n)$
$\Theta(n^2)$
$\Theta(n^4)$
Explanation. $4^{\log_2 n}=n^{\log_2 4}=n^2$ leaves; the internal levels sum to $n(1+2+\dots+2^{\log_2 n-1})<n\cdot n$. When costs grow, the leaves dominate.
In the recursion tree of $T(n)=a\,T(n/b)+f(n)$ the leaves cost $\Theta(n^{\log_b a})$ in all and the root $f(n)$. For $T(n)=9T(n/3)+n$, which part dominates and what is the solution?
The leaves: $T(n)=\Theta(n^2)$
The root: $T(n)=\Theta(n)$
All levels alike: $\Theta(n\log n)$
The leaves: $T(n)=\Theta(n^3)$
Explanation. $n^{\log_3 9}=n^2$ grows faster than $f(n)=n$: level costs grow by a factor $9/3=3$, and the leaves dominate. $n^3$ mistakes $a$ for the exponent.
Towards the Master theorem: in the tree of $T(n)=a\,T(n/b)+f(n)$ one compares $f(n)$ with $n^{\log_b a}$. What happens when $f(n)=\Theta(n^{\log_b a})$?
The root dominates: $T(n)=\Theta(f(n))$
$T(n)=\Theta(n^{\log_b a}\log n)$
The leaves dominate: $T(n)=\Theta(n^{\log_b a})$
$T(n)=\Theta(f(n)\cdot n^{\log_b a})$
Explanation. With equal costs per level one multiplies the cost of a level by the number of levels, as in $2T(n/2)+n=\Theta(n\log n)$. It is case 2 of the Master theorem.
To which of these recurrences does the Master Theorem not apply?
$T(n)=2T(n/2)+n\log_2 n$
$T(n)=4T(n/2)+n^2$
$T(n)=3T(n/4)+n\log_2 n$
$T(n)=2T(n/2)+n/\log_2 n$
Explanation. $n/\log_2 n$ is smaller than $n^{\log_2 2}=n$ but not polynomially, and it is not of the form $n\log^k n$ with $k\ge0$: it falls in the gap between cases 1 and 2 (solution $\Theta(n\log\log n)$). With $n\log_2 n$ for $a=b=2$ and $4T(n/2)+n^2$ we are in case 2, with $3T(n/4)+n\log_2 n$ in case 3.
Why does the Master Theorem not apply to $T(n)=T(n-1)+n$?
Because $a=1$, while the theorem requires at least two subproblems, i.e., $a\ge 2$.
Because the subproblem has size $n-1$ and not $n/b$ with a constant $b>1$: the recurrence is not in standard form.
Because $f(n)=n$ grows too much with respect to $n^{\log_b a}$ and is not asymptotically positive.
Because $f(n)=n$ falls into case 3, but the regularity condition fails.
Explanation. The theorem requires $T(n)=a\,T(n/b)+f(n)$ with constants $a\ge 1$ and $b>1$: $a=1$ is allowed. The recurrence is solved by expansion: $\Theta(n^2)$.
In case 3 of the Master Theorem, besides $f(n)=\Omega(n^{\log_b a+\epsilon})$, which condition is required?
$a\,f(n/b)\le c\,f(n)$ for some constant $c<1$ and all sufficiently large $n$ (regularity condition).
$f(n/b)\le f(n)$ for all $n$, i.e., $f$ non-decreasing (monotonicity condition).
$a\,f(n/b)\ge c\,f(n)$ for some constant $c>1$ and all sufficiently large $n$.
$f(n)=\bigO(n^{\log_b a})$, so that root and leaves have the same order.
Explanation. The regularity condition says that the cost of the levels decreases geometrically from the root to the leaves, so the root dominates: $T(n)=\Theta(f(n))$.
Using the Master Theorem, what is the solution of $T(n)=7\,T(n/2)+n^2$?
$\Theta(n^2)$
$\Theta(n^2\log n)$
$\Theta(n^{\log_2 7})$
$\Theta(n^3)$
Explanation. $n^{\log_2 7}\approx n^{2.81}$ and $f(n)=n^2=\bigO(n^{\log_2 7-\epsilon})$ with $\epsilon=\log_2 7-2>0$: case 1. This is the recurrence of Strassen's algorithm, which beats $\Theta(n^3)$.
Let $a\ge 1$, $b>1$ be constants and $T(n)=a\,T(n/b)+f(n)$. Which statement of the Master Theorem is correct?
If $f(n)=\Theta(n^{\log_b a}\log^k n)$ for some constant $k\ge 0$, then $T(n)=\Theta(n^{\log_b a}\log^{k} n)$.
If $f(n)=\bigO(n^{\log_b a})$, then $T(n)=\Theta(n^{\log_b a})$.
If $f(n)=\Omega(n^{\log_b a+\epsilon})$ for some constant $\epsilon>0$, then $T(n)=\Theta(f(n))$, with no further condition.
If $f(n)=\Theta(n^{\log_b a}\log^k n)$ for some constant $k\ge 0$, then $T(n)=\Theta(n^{\log_b a}\log^{k+1} n)$.
Explanation. This is case 2: all the $\log_b n$ levels cost of the order of $f(n)$, and one more factor $\log n$ appears. Case 1 requires $f$ to be polynomially smaller ($n^{\log_b a-\epsilon}$), case 3 also the regularity condition.
Which statement about the base of the logarithms in the Master Theorem is correct?
The base is irrelevant everywhere: $n^{\log_2 4}=\Theta(n^{\log_4 4})$.
Inside $\Theta$ the base of the logarithm in $\log^k n$ is irrelevant, while the base $b$ in the exponent of $n^{\log_b a}$ is essential.
The base is essential everywhere: $\log_2 n$ and $\log_3 n$ have different orders of growth.
The theorem holds only with logarithms in base $2$.
Explanation. $\log_c n=\log_2 n/\log_2 c$ differs from $\log_2 n$ by a constant factor; instead $n^{\log_2 4}=n^2$ and $n^{\log_4 4}=n$, and $n^2\ne\Theta(n)$.
We want to prove the Master Theorem for $T(n)=a\,T(n/b)+f(n)$ ($a\ge1$, $b>1$) when $n$ is an exact power of $b$. Which results are used?
The bounds on $\lceil n/b\rceil$ and on $\lceil\lceil n/b\rceil/b\rceil$, needed to follow the sizes of the subproblems.
Only the fact that the regularity condition $a\,f(n/b)\le c\,f(n)$ implies $f(n)=\Omega(n^{\log_b a+\epsilon})$.
The substitution method with the guess $T(n)\le c\,n^{\log_b a}$, which covers the three cases together.
$T(n)=\Theta(n^{\log_b a})+\sum_{j=0}^{\log_b n-1}a^jf(n/b^j)$ (leaves plus levels), and a bound on the sum in the three cases.
Explanation. The first formula separates the cost of the leaves from that of the internal levels, the bound on the sum handles the three cases; then the two terms are compared. Ceilings are needed only to extend the result to every $n$.
Let $T(1)=d$ and $T(n)=a\,T(n/b)+f(n)$ for $n$ a power of $b$. In the recursion tree, what is needed to write the cost of the leaves as $\Theta(n^{\log_b a})$?
The geometric series with ratio $b^\epsilon$, which in case 1 is dominated by its last term.
The expansion $T(n)=a^iT(n/b^i)+\sum_{j<i}a^jf(n/b^j)$ up to $i=\log_b n$, and $a^{\log_b n}=n^{\log_b a}$.
The regularity condition $a\,f(n/b)\le c\,f(n)$ with $c<1$, applied level by level.
The fact that there are $n$ leaves, one per element, each of cost $d$.
Explanation. With $i=\log_b n$ we reach $T(1)=d$ and the first term is $d\,a^{\log_b n}=d\,n^{\log_b a}$; the leaves are $n$ only when $a=b$. The geometric series and the regularity condition bound the sum over the levels.
Karatsuba's algorithm multiplies two $n$-digit integers with $3$ recursive multiplications of $n/2$-digit integers and linear work to divide and combine. Writing the recurrence in standard form $T(n)=a\,T(n/b)+f(n)$, what are $a$, $b$ and $f(n)$?
$a=2$, $b=3$, $f(n)=n$
$a=3$, $b=2$, $f(n)=n$
$a=3$, $b=3$, $f(n)=n$
$a=3$, $b=2$, $f(n)=n^2$
Explanation. $a$ is the number of subproblems ($3$), $n/b$ their size ($n/2$), $f(n)$ the work outside the calls ($\Theta(n)$). The Master Theorem gives $T(n)=\Theta(n^{\log_2 3})$.
A recurrence is in standard form if it can be written $T(n)=a\,T(n/b)+f(n)$ with constants $a\ge 1$, $b>1$ and $f$ asymptotically positive ($n/b$ may also mean $\lfloor n/b\rfloor$ or $\lceil n/b\rceil$). Which of the following is not in standard form?
$T(n)=2\,T(\lfloor n/2\rfloor)+n$
$T(n)=T(n/2)+1$
$T(n)=16\,T(n/4)+n^2\log_2 n$
$T(n)=\frac12\,T(n/2)+n$
Explanation. With $a=\frac12<1$ there would be less than one subproblem: the condition $a\ge 1$ fails. Floors are allowed, and $a=1$ (binary search) is fine.
With the Master Theorem (case 2: if $f(n)=\Theta(n^{\log_b a}\log^k n)$ with $k\ge 0$ then $T(n)=\Theta(n^{\log_b a}\log^{k+1}n)$), what is the solution of $T(n)=4\,T(n/2)+n^2\log_2 n$?
$\Theta(n^2\log n)$
$\Theta(n^2)$
$\Theta(n^2\log^2 n)$
$\Theta(n^3)$
Explanation. $n^{\log_2 4}=n^2$ and $f(n)=n^2\log n$ has the form $n^{\log_b a}\log^k n$ with $k=1$: case 2 adds a logarithmic factor, $T(n)=\Theta(n^2\log^2 n)$. $f$ is not polynomially larger than $n^2$, so it is not case 3.
For $T(n)=2\,T(n/2)+n^2$ we have $f(n)=n^2=\Omega(n^{\log_2 2+\epsilon})$; case 3 of the Master Theorem also requires the regularity condition $a\,f(n/b)\le c\,f(n)$ with a constant $c<1$. Which constant satisfies it, and which solution is obtained?
$c=\frac12$; $T(n)=\Theta(n^2)$
$c=\frac14$; $T(n)=\Theta(n^2)$
$c=2$; $T(n)=\Theta(n^2\log n)$
None: the condition fails and the theorem does not apply
Explanation. $a\,f(n/b)=2\,(n/2)^2=\frac12 n^2$, so it holds with $c=\frac12$ (not with $c=\frac14$, which would require $\frac12 n^2\le\frac14 n^2$). In case 3 the root dominates: $T(n)=\Theta(f(n))=\Theta(n^2)$.
The proof of the Master theorem first works with $n$ an exact power of $b$. Which fact then allows extending the bounds to all $n$?
Every natural is a power of $b$
Floors and ceilings never change the value of $T$
Case 3 needs no extension
For regular functions, what holds on powers of $b$ holds for all $n$
Explanation. Between consecutive powers $b^j \le n<b^{j+1}$ monotone functions change by at most a constant factor, absorbed by $O$ and $\Omega$. Floors and ceilings are treated separately.
In the proof of the Master theorem, $g(n)=\sum_{j=0}^{\log_b n-1} a^j f(n/b^j)$ is the cost of the internal levels of the recursion tree, with $p=\log_b a$. Which statement is correct?
If $f(n)=\Theta(n^p)$ then $g(n)=\Theta(n^p\log_b n)$
$g(n)=\Theta(f(n))$ always
If $f(n)=\Theta(n^p)$ then $g(n)=\Theta(n^p)$
$g(n)$ does not depend on $f$
Explanation. In the first case the levels form a geometric series dominated by the leaves; in the second all $\log_b n$ levels cost $\Theta(n^p)$, hence the logarithmic factor.
With the recurrence $T(n)=aT(\lceil n/b\rceil)+f(n)$ the subproblem sizes at level $j$ are $n_j$, with $n_0=n$ and $n_{j+1}=\lceil n_j/b\rceil$. With $n=10$ and $b=2$, what is $n_3$?
$1$
$1.25$
$2$
$3$
Explanation. $n_1=\lceil 10/2\rceil=5$, $n_2=\lceil 5/2\rceil=3$, $n_3=\lceil 3/2\rceil=2$. Without ceilings one would get $10/8=1.25$: ceilings add at most a constant.
Which statement about the Master theorem with ceilings ($T(n)=aT(\lceil n/b\rceil)+f(n)$) is correct?
The same three cases hold, for every $n$
It holds only for $n$ a power of $b$
Only case 2 holds
The result changes by a factor $\log_b n$
Explanation. Ceilings change the subproblem sizes by a bounded amount, and the three cases stay the same. This is why floors and ceilings are ignored in applications.
In case 3 of the Master theorem the regularity condition $a\,f(n/b) \le c\,f(n)$ with $c<1$ is required. Observation: it implies $f(n)=\Omega(n^{p+\epsilon})$, with $p=\log_b a$. Why?
Because $c<1$ makes $f$ decreasing
Because $f$ is a polynomial
Iterating it: $f(n) \ge (a/c)^j f(n/b^j)$
Because regularity holds only for constant $f$
Explanation. With $j=\log_b n$ levels one gets $f(n) \ge \Theta(n^{\log_b(a/c)})$, and $\log_b(a/c)=p+\log_b(1/c)>p$. So regularity makes the second condition of case 3 redundant.
RecursiveBinarySearch examines the middle element and then calls itself on one half only, with constant work per call. Which parameters does its standard-form recurrence $T(n)=a\,T(n/b)+f(n)$ have?
$a=2$, $b=2$, $f(n)=\Theta(1)$
$a=1$, $b=2$, $f(n)=\Theta(n)$
$a=2$, $b=1$, $f(n)=\Theta(1)$
$a=1$, $b=2$, $f(n)=\Theta(1)$
Explanation. One subproblem ($a=1$) of half size ($b=2$), with one comparison and one computation of $mid$ ($f(n)=\Theta(1)$): $T(n)=\Theta(\log n)$. $a=2$ would also count the discarded half.
In the standard form $T(n)=a\,T(n/b)+f(n)$ of the Master theorem one requires constants $a\ge 1$ and $b>1$. What do these two conditions guarantee?
At least one subproblem, smaller than the instance
That the solution $T(n)$ is always polynomial
That the function $f(n)$ is increasing
That the tree has exactly $a$ levels
Explanation. $a$ is the number of subproblems and $n/b$ their size: with $b>1$ the size decreases by a constant factor, and the tree has $\log_b n$ levels.
Rule of thumb of the Master theorem for $T(n)=a\,T(n/b)+f(n)$: compare $f(n)$ with $n^{\log_b a}$, and the larger term wins (if they have the same order, multiply by $\log n$). What is the solution of $T(n)=3T(n/2)+n^2$?
$\Theta(n^{\log_2 3})$
$\Theta(n^2\log n)$
$\Theta(n^2)$
$\Theta(n^3)$
Explanation. $n^{\log_2 3}\approx n^{1.58}$ is polynomially smaller than $n^2$: case 3, with regularity $3(n/2)^2=\frac34 n^2$. Hence $T(n)=\Theta(n^2)$.
With the rule of thumb of the Master theorem (compare $f(n)$ with $n^{\log_b a}$; for equal orders multiply by $\log n$), what is the solution of $T(n)=4T(n/2)+n^2$?
$\Theta(n^2\log n)$
$\Theta(n^2)$
$\Theta(n^4)$
$\Theta(n\log n)$
Explanation. $n^{\log_2 4}=n^2$, of the same order as $f(n)=n^2$: case 2, $\Theta(n^2\log n)$. Every level of the tree costs $n^2$, and there are $\log_2 n$ levels.
In the recursion tree of $T(n)=a\,T(n/b)+f(n)$ there are $a^{\log_b n}$ leaves. Why does the term $n^{\log_b a}$ of the Master theorem measure the cost of the leaves?
Because the tree has $n^{\log_b a}$ levels
Because the root costs $n^{\log_b a}$
Because $a^{\log_b n}=n^{\log_b a}$
Because each level has $n$ nodes of cost $\Theta(1)$
Explanation. Both equal $2^{\log_2 a\cdot\log_2 n/\log_2 b}$. The Master theorem thus compares the cost of the leaves with the cost $f(n)$ of the root.
For $T(n)=a\,T(n/b)+n^k$, level $j$ of the recursion tree costs $a^j(n/b^j)^k=(a/b^k)^j n^k$. With $a=8$, $b=2$, $k=2$, how do level costs change and what is the solution?
They stay equal: $\Theta(n^2\log n)$
They double: $\Theta(n^3)$
They halve: $\Theta(n^2)$
They grow by a factor $8$: $\Theta(n^8)$
Explanation. $a/b^k=8/4=2>1$: costs grow geometrically towards the leaves, which are $n^{\log_2 8}=n^3$ (case 1). Ratio $1$ would give case 2, ratio below $1$ case 3.
Case 1 of the Master theorem asks $f(n)$ to be polynomially smaller than $n^{\log_b a}$. What does it mean?
$f(n)=\bigO(n^{\log_b a})$, with any constant
$f(n)=o(n^{\log_b a})$
$f(n)\le n^{\log_b a}$ for every $n\ge 1$
$f(n)=\bigO(n^{\log_b a-\epsilon})$ with $\epsilon>0$
Explanation. A margin of a factor $n^\epsilon$ is needed. Being only $o(n^{\log_b a})$ is not enough: $n/\log n=o(n)$ but it is not $\bigO(n^{1-\epsilon})$ for any $\epsilon>0$, and it falls into a gap between the cases.
For $T(n)=2T(n/2)+f(n)$ we have $n^{\log_2 2}=n$. With $f(n)=n^2/\log_2 n$, the ratio $f(n)/n=n/\log_2 n$ grows. Can case 3 be applied (it requires $f(n)=\Omega(n^{1+\epsilon})$ and regularity)?
No: $f$ falls into a gap between the cases
Yes: $n^2/\log_2 n=\Omega(n^{1.5})$, and regularity holds
No: case 3 requires exactly $f(n)=n^2$
Yes, but the solution is $\Theta(n\log n)$
Explanation. $\epsilon=\frac12$ suffices: $n^2/\log_2 n\ge n^{1.5}$ for large $n$. Regularity: $2f(n/2)=\frac{n^2}{2\log_2(n/2)}\le\frac{1}{2}\cdot\frac{n^2}{\log_2 n}\cdot\frac{\log_2 n}{\log_2 n-1}$, which is $\le\frac34 f(n)$ for large $n$. Hence $T(n)=\Theta(n^2/\log n)$.
The recurrence $T(n)=2T(n/2)+n\log_{10} n$ uses a base-$10$ logarithm. Knowing that the extended case 2 of the Master theorem gives $T(n)=\Theta(n^{\log_b a}\log^{k+1} n)$ when $f(n)=\Theta(n^{\log_b a}\log^k n)$, $k\ge 0$, what is the solution?
$\Theta(n\log n)$
$\Theta(n\log_{10} n)$
It does not apply, because of base $10$
$\Theta(n\log^2 n)$
Explanation. $\log_{10} n=\log_2 n/\log_2 10$ differs from $\log_2 n$ by a constant, so $f(n)=\Theta(n\log n)$: case 2 with $k=1$. Inside $\Theta$ the base of the logarithm does not matter.
With the Master theorem, what is the solution of $T(n)=2T(n/4)+\sqrt n$?
$\Theta(\sqrt n)$
$\Theta(n)$
$\Theta(\sqrt n\,\log n)$
$\Theta(\log n)$
Explanation. $n^{\log_4 2}=n^{1/2}=\sqrt n$, of the same order as $f(n)$: case 2, $\Theta(\sqrt n\log n)$. Forgetting the $\log n$ factor is the typical case-2 mistake.
The Master theorem does not apply to $T(n)=T(n-1)+n$ nor to $T(n)=T(n/3)+T(2n/3)+n$. How is the order of growth found then?
It cannot be found by any method
With another method (expansion, tree, substitution)
Case 2 of the theorem is applied anyway
One rounds $n-1$ to $n/2$ and applies the theorem
Explanation. Expansion gives $T(n)=\Theta(n^2)$ for the first; the recursion tree gives $\Theta(n\log n)$ for the second. Rounding the recurrence would change the solution.
The proof of the Master theorem first works with $n$ an exact power of $b$. Why does this hypothesis simplify the computation?
Because then the function $f(n)$ is constant
Because then $a$ and $b$ coincide
Because the leaves become exactly $n$
The sizes $n/b^j$ are all integers
Explanation. With $n=b^h$ every subproblem has integer size $b^{h-j}$ and all leaves are at level $h$. The general case then follows with floors and ceilings.
In the recursion tree of $T(n)=a\,T(n/b)+f(n)$, with $n$ a power of $b$, how many nodes does level $j$ have and how much does each cost?
$b^j$ nodes, each costing $f(n/a^j)$
$a^j$ nodes, each costing $f(n/b^j)$
$a^j$ nodes, each costing $f(n)/a^j$
$j$ nodes, each costing $f(n/b)$
Explanation. Each node has $a$ children, and going down one level the size is divided by $b$. The total cost is $\Theta(n^{\log_b a})+\sum_{j=0}^{\log_b n-1}a^j f(n/b^j)$.
In the proof of the Master theorem, $g(n)=\sum_{j=0}^{\log_b n-1}a^j f(n/b^j)$. In case 2, $f(n)=\Theta(n^{\log_b a})$. What is each term $a^j f(n/b^j)$, and hence $g(n)$?
The terms decrease, so $g(n)=\Theta(f(n))$
The terms increase, so $g(n)=\Theta(n^{\log_b a})$
Each term is $\Theta(1)$, so $g(n)=\Theta(\log n)$
Each term is $\Theta(n^{\log_b a})$, so $g(n)=\Theta(n^{\log_b a}\log n)$
Explanation. $a^j(n/b^j)^{\log_b a}=a^j\,n^{\log_b a}/a^j=n^{\log_b a}$: the $\log_b n$ levels all cost the same.
For $n$ a power of $b$, $T(n)=\Theta(n^{\log_b a})+g(n)$, where $g(n)$ is the cost of the internal levels. In case 3 one proves $g(n)=\Theta(f(n))$, with $f(n)=\Omega(n^{\log_b a+\epsilon})$. Why then is $T(n)=\Theta(f(n))$?
Because the cost of the leaves is $\bigO(f(n))$
Because in case 3 there are no leaves
Because $f(n)=\Theta(n^{\log_b a})$
Because $g(n)$ is always larger than $T(n)$
Explanation. $n^{\log_b a}=\bigO(n^{\log_b a+\epsilon})=\bigO(f(n))$, so the sum of the two terms is $\Theta(f(n))$: the root dominates.
Case 3 of the Master theorem needs the regularity condition: $a\,f(n/b)\le c\,f(n)$ for a constant $c<1$ and large $n$. For $T(n)=3T(n/2)+n^2$, which constant $c$ is obtained?
$c=\frac32$
$c=\frac12$
$c=\frac34$
$c=3$
Explanation. $3\,(n/2)^2=\frac34 n^2$, so the condition holds with $c=\frac34<1$. $\frac32$ forgets to square the factor $\frac12$.
RecursiveSum$(a,l,r)$ returns $a[l]$ if $l=r$, otherwise RecursiveSum$(a,l,m)+$RecursiveSum$(a,m+1,r)$ with $m=\lfloor(l+r)/2\rfloor$. It is called on a sub-array of $n=8$ elements. How many calls does it execute in total and what is the recursion depth?
$15$ calls, depth $3$
$8$ calls, depth $4$
$15$ calls, depth $4$
$16$ calls, depth $8$
Explanation. The calls are $2n-1=15$ ($n$ base cases and $n-1$ additions); the tree has height $\lceil\log_2 n\rceil=3$, hence depth $\lceil\log_2 n\rceil+1=4$.
RecursiveSumLinear$(a,n)$ returns RecursiveSumLinear$(a,n-1)+a[n]$ (with base case $n=0$); RecursiveSum recursively adds the two halves of the array. How much call-stack memory do they use, with frames of constant size?
$\Theta(n)$ and $\Theta(\log_2 n)$
$\Theta(\log_2 n)$ for both
$\Theta(n)$ for both
$\Theta(1)$ and $\Theta(\log_2 n)$
Explanation. Both execute $\Theta(n)$ steps, but the recursion depth is $n$ for the decrease by one and $\lceil\log_2 n\rceil+1$ for the halving.
MergeSort sorts $a[l..r]$ by recursively sorting the two halves and merging them with Merge, which copies the halves into two auxiliary arrays $L$ and $R$. Which statement is correct?
It executes $\Theta(n\log_2 n)$ steps and it is in-place, like Insertion Sort.
It executes $\Theta(n^2)$ steps in the worst case, like Insertion Sort.
It executes $\Theta(n\log_2 n)$ steps in the worst case and uses $\Theta(n)$ extra memory: it is not in-place.
It uses only $\Theta(\log_2 n)$ extra memory, that of the call stack.
Explanation. $S(n)=2S(n/2)+\Theta(n)$ gives $\Theta(n\log_2 n)$; Merge allocates the arrays $L$ and $R$, up to $n$ elements in the first call, plus $\Theta(\log_2 n)$ for the stack.
Recursive binary search examines the central element and calls itself on one half, with $S(n)=S(\lfloor n/2\rfloor)+c$ steps. On an array of $n$ entries of constant size, what is the worst-case running time as a function of the number of bits of the input $|I|$?
$T(|I|)=\Theta(\log|I|)$
$T(|I|)=\Theta(|I|)$
$T(|I|)=2^{\Theta(|I|)}$
$T(|I|)=\Theta(|I|\log|I|)$
Explanation. $S(n)=S(\lfloor n/2\rfloor)+c$ gives $S(n)=\Theta(\log_2 n)$, and for an array $|I|=\Theta(n)$: the running time is logarithmic in the input size.
Maximum subarray problem on $a[1..n]$: brute force tries all pairs $l\le r$ updating the sum, FindMaximumSubarray is divide and conquer (two halves plus the crossing subarrays), Kadane makes a single scan. What is their worst-case order of growth?
Brute force $\Theta(n^3)$, FindMaximumSubarray $\Theta(n^2)$, Kadane $\Theta(n\log_2 n)$
Brute force $\Theta(n^2)$, FindMaximumSubarray $\Theta(n\log_2 n)$, Kadane $\Theta(n)$
All three $\Theta(n\log_2 n)$
Brute force $\Theta(n^2)$, FindMaximumSubarray $\Theta(n)$, Kadane $\Theta(n)$
Explanation. The brute force tries all pairs $l\le r$ updating the sum; FindMaximumSubarray satisfies $S(n)=2S(n/2)+\Theta(n)$ (case 2); Kadane makes a single scan.
In the divide and conquer algorithm for the maximum subarray, FindMaxCrossingSubarray$(a,l,mid,r)$, with $l\le mid<r$ and $n=r-l+1$, handles the subarrays crossing the midpoint. Which statement is correct?
It finds a maximum-sum subarray of the whole $a[l..r]$, in $\Theta(n)$ steps, with two scans.
It finds the maximum-sum subarray ending at $a[mid]$, in $\Theta(\log n)$ steps.
It finds a maximum-sum subarray among those containing $a[mid]$, in $\Theta(n^2)$ steps.
It finds a maximum-sum subarray among those containing $a[mid]$ and $a[mid+1]$, in $\Theta(n)$ steps.
Explanation. The left and right parts of a subarray crossing the midpoint can be chosen independently, with two linear scans. The maximum over the whole $a[l..r]$ is obtained only by comparing with the two recursive results.
RecursiveBinarySearch$(a,l,r,m)$ returns $-1$ if $l>r$ (empty interval); otherwise it examines $mid=\lfloor(l+r)/2\rfloor$ and, if $a[mid]\ne m$, calls itself on $[l,mid-1]$ or on $[mid+1,r]$. Which statement about the calls of RecursiveBinarySearch$(a,1,n,m)$, $n\ge 1$, is correct?
At most $\lfloor\log_2 n\rfloor+1$ calls are on a non-empty interval, and in total there are at most $\lfloor\log_2 n\rfloor+2$ calls.
There are exactly $\lceil\log_2 n\rceil$ calls on every input, both with $m$ present and with $m$ absent.
There are at most $n/2$ calls, because each call discards at least two elements of the interval.
There are at most $\log_2 n$ calls, including the one on an empty interval.
Explanation. Observation 17.7: the interval is at least halved at each call, and after the last non-empty call at most one call on an empty interval can follow. The bound is attained, for instance, with $m>a[n]$.
MergeSort$(a,l,r)$, if $l<r$, recursively sorts $a[l..m]$ and $a[m+1..r]$ and merges them with Merge. What is used to prove its correctness?
The invariant of the inner loop of Insertion Sort, applied to each merge of the two sorted halves.
The Master Theorem applied to $S(n)=2S(n/2)+\Theta(n)$, which also guarantees termination.
Strong induction on the number $k=r-l+1$ of elements and the correctness of Merge, proved with a loop invariant.
Simple induction from $k-1$ to $k$ elements, since each call removes at least one element.
Explanation. By the inductive hypothesis the two calls (with between $1$ and $k-1$ elements) sort $a[l..m]$ and $a[m+1..r]$; so the precondition of Merge holds, and it produces $a[l..r]$ sorted. The Master Theorem concerns the number of steps, not correctness.
FindMaximumSubarray$(a,l,r)$ recursively looks for the maximum-sum subarray in the two halves, the one crossing the midpoint with FindMaxCrossingSubarray, and returns the best of the three. What is needed to prove its correctness?
Strong induction; every subarray is on the left, on the right or crossing; correctness of FindMaxCrossingSubarray.
Only the correctness of FindMaxCrossingSubarray: the maximum-sum subarray always crosses the midpoint.
The invariant of Kadane: $cur$ is the maximum sum of a subarray ending at the current position.
The assumption that the array contains at least one positive element, without which the maximum is undefined.
Explanation. By the inductive hypothesis the two calls find the maximum of the subarrays of the first two types, FindMaxCrossingSubarray that of the third type; the maximum of the three is the answer. The maximum does not always cross the midpoint.
An algorithm is tail recursive if it returns unchanged the result of its last call. RecursiveBinarySearch makes a single call on one half; RecursiveSum adds the results on the two halves; MergeSort calls Merge after the two calls; FindMaximumSubarray compares three results. Which one is tail recursive?
RecursiveSum
MergeSort
RecursiveBinarySearch
FindMaximumSubarray
Explanation. RecursiveBinarySearch directly returns the value of its only call (Definition 17.8). RecursiveSum adds two results, MergeSort calls Merge after the calls, FindMaximumSubarray compares three results.
FindMaximumSubarray solves the maximum subarray problem by divide and conquer: two calls on the halves and a linear scan for the subarrays crossing the midpoint, without auxiliary arrays. How many steps does it perform in the worst case and how much extra memory does it use (call stack included)?
$\Theta(n\log_2 n)$ steps and $\Theta(n)$ memory
$\Theta(n)$ steps and $\Theta(1)$ memory
$\Theta(n^2)$ steps and $\Theta(\log_2 n)$ memory
$\Theta(n\log_2 n)$ steps and $\Theta(\log_2 n)$ memory
Explanation. $S(n)=2S(n/2)+\Theta(n)$ gives $\Theta(n\log_2 n)$, as for MergeSort; but without the arrays $L$ and $R$ of Merge the memory is only the stack, proportional to the depth $\Theta(\log_2 n)$. $\Theta(n)$ and $\Theta(1)$ are those of Kadane.
Ignoring multiplicative constants: InsertionSort performs $n^2$ steps and MergeSort $n\log_2 n$, on a computer that executes $10^9$ steps per second. About how much time do they need with $n=10^6$?
About $1$ second and about $0.001$ seconds
About $1000$ seconds and about $0.02$ seconds
About $1000$ seconds and about $20$ seconds
About $10^6$ seconds and about $0.02$ seconds
Explanation. $n^2=10^{12}$ steps, i.e., $10^3$ seconds; $n\log_2 n\approx 10^6\cdot 20=2\cdot 10^7$ steps, i.e., $0.02$ seconds. Since $n\log_2 n=o(n^2)$, the gap grows with $n$.
RecursiveSum$(a,l,r)$ returns $a[l]$ if $l=r$, otherwise with $m=\lfloor(l+r)/2\rfloor$ it returns RecursiveSum$(a,l,m)+$RecursiveSum$(a,m+1,r)$. On which quantity is induction done to prove it correct?
On the value of the sum
On the number of elements $r-l+1$
On the index $l$ only
On the number of bits of $a[l]$
Explanation. Both calls work on sub-arrays with fewer elements (for $l<r$), so the strong inductive hypothesis applies to both; the base case is a single element.
The call tree of RecursiveSum (which halves the sub-array until one element is left) on $n=10$ elements has height $\lceil\log_2 n\rceil$. What is the recursion depth, that is, the maximum number of calls active at the same time?
$4$
$10$
$19$
$5$
Explanation. Height $\lceil\log_2 10\rceil=4$, depth $4+1=5$ (the initial call also counts). $19=2n-1$ is the total number of calls.
Merge merges the sorted $a[l..m]$ and $a[m+1..r]$, writing at position $k$ the smaller of the two current elements. Which invariant, true at the start of every iteration, proves it correct?
The two halves stay sorted and disjoint
$a[l..k-1]$ holds, sorted, the $k-l$ smallest elements
$k$ always equals $m$
The array $a[l..r]$ is already sorted
Explanation. The invariant describes the partial result; at the end (all positions written) it gives the sorting of $a[l..r]$. The array is not sorted before the end.
Let $a[1..n]$ be sorted in nondecreasing order. Which statement about recursive binary search RecursiveBinarySearch$(a,left,right,m)$ is correct?
It also works if the array is not sorted
It always returns the first occurrence of $m$
It does not terminate if $m$ does not occur
It finds $m$ if it occurs in $a[left..right]$, else signals absence
Explanation. Correctness requires a sorted array: every comparison with the middle element discards a half that cannot contain $m$. With duplicates it may find any occurrence.
Kadane's algorithm scans the array keeping $cur$ (maximum sum of a sub-array ending at the previous position) and $best$ (best sum seen so far). Which update makes the invariant on $cur$ true at position $i$?
$cur:=cur+a[i]$ always
$cur:=\max\{cur,a[i]\}$
$cur:=\max\{cur+a[i],\,a[i]\}$
$cur:=best+a[i]$
Explanation. A sub-array ending at $i$ is $a[i]$ alone or a sub-array ending at $i-1$ plus $a[i]$; the better of the two is the maximum. Then $best:=\max\{best,cur\}$.
SumIterative$(a,n)$ starts from $s:=0$ and also works with $n=0$. RecursiveSum$(a,l,r)$ (returns $a[l]$ if $l=r$, otherwise adds up the two halves) instead requires $l\le r$. What would happen calling it on an empty sub-array, with $l>r$?
The base case $l=r$ is never reached
It returns $0$, the empty sum
It returns $a[l]$, as in the base case
It returns $-1$, as search does
Explanation. With $l>r$ one gets $m=\lfloor(l+r)/2\rfloor$ and one of the two calls again receives an invalid interval: the recursion never reaches the base case, which is a one-element sub-array.
To add up $n\ge 1$ numbers with additions of two numbers at a time, SumIterative (starts from $s:=0$ and adds $a[1],\dots,a[n]$) and RecursiveSum (one addition $s_1+s_2$ per non-base call) perform how many additions?
$n-1$ and $n-1$
$n$ and $2n-1$
$n$ and $n-1$
$n$ and $\log_2 n$
Explanation. SumIterative makes one addition per element, including the first $0+a[1]$. RecursiveSum has $2n-1$ calls, $n$ of them leaves: the $n-1$ internal calls make one addition each.
SumIterative$(a,n)$: $s:=0$, $i:=1$, while $i\le n$ it runs $s\leftarrow s+a[i]$ and $i\leftarrow i+1$, then returns $s$. Counting each executed line once (the while condition is evaluated $n+1$ times), how many steps does it perform with $n=10$?
$30$
$33$
$44$
$34$
Explanation. $1+1+(n+1)+n+n+1=3n+4=34$. $33$ forgets the last evaluation of the condition, the false one that exits the loop.
RecursiveSum$(a,l,r)$ returns $a[l]$ if $l=r$, otherwise with $m=\lfloor(l+r)/2\rfloor$ returns RecursiveSum$(a,l,m)+$RecursiveSum$(a,m+1,r)$. Which two calls does RecursiveSum$(a,1,7)$ make?
$(a,1,3)$ and $(a,4,7)$
$(a,1,4)$ and $(a,5,7)$
$(a,1,3)$ and $(a,5,7)$
$(a,1,6)$ and $(a,7,7)$
Explanation. $m=\lfloor 8/2\rfloor=4$: the left half has $\lceil 7/2\rceil=4$ elements, the right one $3$. The two halves cover all of $a[1..7]$ without overlapping.
In RecursiveSum$(a,l,r)$, with $k=r-l+1\ge 2$ elements, the two halves $a[l..m]$ and $a[m+1..r]$ ($m=\lfloor(l+r)/2\rfloor$) have $\lceil k/2\rceil$ and $\lfloor k/2\rfloor$ elements. Why does this guarantee termination?
Because $k$ is always a power of $2$
Because the right half is always empty
Because at most two calls are made in all
Each half has between $1$ and $k-1$ elements
Explanation. For $k\ge 2$, $1\le\lfloor k/2\rfloor\le\lceil k/2\rceil\le k-1$: each call receives a non-empty, shorter sub-array, down to the base case $l=r$.
RecursiveSum$(a,l,r)$ first calls the left half $(l,m)$ and then the right one $(m+1,r)$, with $m=\lfloor(l+r)/2\rfloor$. In which order do the calls of RecursiveSum$(a,1,4)$ start?
$(1,4),(1,2),(3,4),(1,1),(2,2),(3,3),(4,4)$
$(1,4),(1,2),(1,1),(2,2),(3,4),(3,3),(4,4)$
$(1,1),(2,2),(1,2),(3,3),(4,4),(3,4),(1,4)$
$(1,4),(3,4),(4,4),(3,3),(1,2),(2,2),(1,1)$
Explanation. Calls are visited depth-first: call $(1,2)$ finishes with its children before $(3,4)$ starts. The second order is level by level, the third is the order in which calls finish.
In the call tree of RecursiveSum on $n$ elements, the leaves are the calls on a single element and every internal node has two children. For $n=6$, how many internal nodes are there?
$6$
$11$
$3$
$5$
Explanation. A tree in which every internal node has two children and there are $n$ leaves has $n-1$ internal nodes: $5$, and $11=2n-1$ nodes in all.
In the inductive step of RecursiveSum$(a,l,r)$'s correctness one knows, by the inductive hypothesis, that $s_1=a[l]+\dots+a[m]$ and $s_2=a[m+1]+\dots+a[r]$. Why is $s_1+s_2$ the required sum?
The two halves are disjoint and together form $a[l..r]$
Because $s_1=s_2$ when $m$ is the midpoint
Because addition is commutative and associative
Because $m$ is always an even index
Explanation. $a[l..m]$ and $a[m+1..r]$ share no elements and leave none out: every element of $a[l..r]$ is counted exactly once. The two sums differ in general.
RecursiveSum always splits in half, yet it performs $\Theta(n)$ steps, like SumIterative. Why?
Because the tree has $n$ levels
Because each call scans its whole sub-array
It makes $2n-1$ calls of $\bigO(1)$ steps
Because the recursion depth is $n$
Explanation. The calls are the nodes of the tree ($n$ leaves and $n-1$ internal nodes), and each runs a fixed number of lines. The depth is only $\lceil\log_2 n\rceil+1$.
The recursion depth of RecursiveSum on $n$ elements (halving down to one element) is $\lceil\log_2 n\rceil+1$. What is the largest number of frames on the call stack with $n=1000$?
$11$
$10$
$1000$
$1999$
Explanation. $\lceil\log_2 1000\rceil=10$, plus the initial call: $11$. $1999=2n-1$ is the total number of calls, which however are never all active together.
RecursiveSumLinear$(a,n)$ returns RecursiveSumLinear$(a,n-1)+a[n]$ (base case $n=0$); RecursiveSum splits in half. What do they have in common and what distinguishes them?
Both depth $\Theta(\log n)$; steps $\Theta(n)$ against $\Theta(n\log n)$
Both depth $n+1$; steps $\Theta(n^2)$ against $\Theta(n)$
Both $\Theta(n)$ steps; depth $n+1$ against $\lceil\log_2 n\rceil+1$
Nothing: steps and depth both differ
Explanation. Both do constant work per call and make $\Theta(n)$ calls. The decrease-by-one version, however, keeps all $n+1$ calls active together, so it uses $\Theta(n)$ stack memory.
Among the sorting algorithms of the course (Insertion, Exchange, Selection Sort, Merge Sort), which performs $\bigO(n\log n)$ comparisons in the worst case?
Insertion Sort
Selection Sort
Exchange Sort
Merge Sort
Explanation. Merge Sort performs $\Theta(n\log n)$ steps on every input. The other three reach $\frac{n(n-1)}{2}$ comparisons in the worst case (Exchange and Selection Sort on every input).
A sort is comparison-based if it accesses the keys only by comparing them in pairs and copying them. Is Merge Sort comparison-based?
No: Merge adds up the keys of the two halves
Yes: Merge compares $L[i]\le R[j]$ and copies keys
No: Merge Sort uses keys as indices
Yes, but only in the base case
Explanation. The only operations on keys are the comparison $L[i]\le R[j]$ and the copies among $a$, $L$ and $R$; the divide step computes $m$ from the indices, not from the keys.
Merge copies the two sorted halves into $L$ and $R$ and, while both have elements, moves into $a$ the smaller of $L[i]$ and $R[j]$ (comparison $L[i]\le R[j]$); then it copies the rest. How many comparisons does it make with $L=[2,5,9]$ and $R=[3,4,10]$?
$5$
$6$
$3$
$9$
Explanation. $2,3,4,5,9$ are copied with one comparison each; then $L$ is exhausted and $10$ is copied with no comparison. At most $n_1+n_2-1=5$ comparisons are needed.
In Merge, for equal keys, the comparison $L[i]\le R[j]$ copies first the element of $L$ (the left half). Which property does this choice give Merge Sort?
Being in-place
Exactly $n-1$ comparisons
Stability
No extra property
Explanation. The elements of $L$ precede those of $R$ in the input. With $L[i]<R[j]$ an equal record from $R$ would jump ahead, and the sort would no longer be stable.
The number of steps of MergeSort satisfies $T(n)=2T(n/2)+\Theta(n)$, where $\Theta(n)$ is the cost of Merge. What is the solution?
$\Theta(n\log n)$
$\Theta(n)$
$\Theta(n^2)$
$\Theta(\log n)$
Explanation. $n^{\log_2 2}=n$, of the same order as $f(n)$: case 2 of the Master theorem. Every level of the tree costs $\Theta(n)$ and there are $\log_2 n$ levels.
On an already sorted array Insertion Sort performs $\Theta(n)$ steps. How many does Merge Sort perform, in the best and in the worst case?
$\Theta(n)$ in the best, $\Theta(n\log n)$ in the worst
$\Theta(n\log n)$ in the best, $\Theta(n^2)$ in the worst
$\Theta(n\log n)$ in both cases
$\Theta(n)$ in both cases
Explanation. Merge Sort always divides and merges the same way: Merge copies all elements into $L$, $R$ and back into $a$ anyway, so every level costs $\Theta(n)$ even on a sorted input.
Merge copies $a[l..m]$ into $L$ and $a[m+1..r]$ into $R$ before merging, instead of working directly in $a$. Why?
Because $L$ and $R$ make Merge Sort in-place
Writing into $a[k]$ would overwrite elements not yet merged
To be able to sort $L$ and $R$ with Insertion Sort
Because $a$ cannot be modified inside a function
Explanation. The positions of $a$ are filled from the left while the elements of the right half are still there: the copies protect them. The price is $\Theta(n)$ extra memory.
Insertion Sort performs $\Theta(n^2)$ steps in the worst case and $\Theta(n)$ in the best, Merge Sort $\Theta(n\log n)$ always. On which kind of large input is Insertion Sort faster?
On an array in decreasing order
On a random array
On no input
On an already sorted array
Explanation. On the sorted array Insertion Sort makes one comparison per element: $\Theta(n)$ against $\Theta(n\log n)$. On the decreasing array it makes $\frac{n(n-1)}{2}$ shifts.
Comparing Insertion Sort and Merge Sort with respect to memory and stability (in-place: constant extra memory), which statement is correct?
Both in-place; only Merge Sort is stable
Both stable; only Insertion Sort is in-place
Only Merge Sort is stable and in-place
Neither is stable
Explanation. Insertion Sort moves keys within the array with a few variables; Merge Sort uses the arrays $L$ and $R$ ($\Theta(n)$ memory). Both keep the order of equal keys.
RecursiveBinarySearch$(a,l,r,m)$ returns $-1$ if $l>r$; otherwise, with $mid=\lfloor(l+r)/2\rfloor$, returns $mid$ if $a[mid]=m$, calls itself on $(l,mid-1)$ if $a[mid]>m$, on $(mid+1,r)$ otherwise. With $a=[1,3,5,7,9,11,13]$ and $m=11$, how many calls in all and what does RecursiveBinarySearch$(a,1,7,11)$ return?
$3$ calls, returns $6$
$2$ calls, returns $5$
$1$ call, returns $6$
$2$ calls, returns $6$
Explanation. $mid=4$, $a[4]=7<11$: call on $(5,7)$; $mid=6$, $a[6]=11$: it returns $6$.
In RecursiveBinarySearch$(a,l,r,m)$ on a sorted array, if $a[mid]>m$ with $mid=\lfloor(l+r)/2\rfloor$, on which interval does it call itself?
On $(mid+1,r)$
On $(l,mid)$
On $(l,mid-1)$
On $(mid,r)$
Explanation. If $a[mid]>m$, all elements to the right of $mid$ are greater than $m$ too: one searches left, excluding $mid$, already examined (with $(l,mid)$ the interval might not shrink).
RecursiveBinarySearch$(a,l,r,m)$ (returns $-1$ if $l>r$; $mid=\lfloor(l+r)/2\rfloor$; left if $a[mid]>m$, right if $a[mid]<m$) searches $m=5$ in $a=[2,4,6,8]$. How many calls in all, including the initial one?
$3$
$2$
$4$
$1$
Explanation. $(1,4)$: $mid=2$, $4<5$; $(3,4)$: $mid=3$, $6>5$; $(3,2)$: empty interval, returns $-1$. The last call is the base case, and it counts.
RecursiveBinarySearch$(a,l,r,m)$ returns $mid=\lfloor(l+r)/2\rfloor$ as soon as $a[mid]=m$. What does it return on $a=[2,2,2,2,2]$ with $m=2$?
$1$
$5$
$-1$
$3$
Explanation. The very first call finds $a[3]=2$. Binary search returns a position of $m$, not necessarily the first: the problem definition accepts any index $k$ with $a[k]=m$.
In the inductive correctness proof of RecursiveBinarySearch on a sorted array, why can $a[l..mid]$ be discarded when $a[mid]<m$?
Because $a[l..mid]$ is always empty
Because every $a[i]$ with $i\le mid$ is $\le a[mid]<m$
Because $m$ never occurs twice
Because the left half is shorter
Explanation. From the non-decreasing order, $a[i]\le a[mid]$ for $i\le mid$, so none of those elements equals $m$; by the inductive hypothesis the call on $(mid+1,r)$ is correct.
Recursive binary search has recursion depth $\Theta(\log n)$, the iterative one uses a while loop with the variables $left$, $right$, $mid$. How much extra memory do they use (first the recursive, then the iterative)?
$\Theta(1)$ and $\Theta(1)$
$\Theta(n)$ and $\Theta(1)$
$\Theta(\log n)$ and $\Theta(\log n)$
$\Theta(\log n)$ and $\Theta(1)$
Explanation. Each active recursive call takes one frame. The recursive version is tail recursive, however, so it turns into the while loop with no loss.
The price of a stock on days $0,\dots,4$ is $[10,11,7,10,6]$. One buys on some day and sells on a later day. What is the largest gain?
$5$
$3$
$4$
$1$
Explanation. Buy at $7$ (day $2$) and sell at $10$ (day $3$). $5=11-6$ would sell before buying. The daily changes are $[1,-4,3,-4]$, and the largest gain is the maximum sum of a sub-array: $3$.
To maximise the gain by buying a stock and selling it on a later day, why is it not enough to buy at the lowest price and sell at the highest?
Because the highest price is never the last one
Because minimum and maximum can only be found in $\Theta(n^2)$ time
Because the day of the minimum may come after that of the maximum
Because the gain does not depend on the prices
Explanation. With $[10,11,7,10,6]$ the maximum $11$ is on day $1$ and the minimum $6$ on the last. This is why one moves to daily changes and to the maximum-sum sub-array.
The maximum-subarray problem asks, given $a[1..n]$, for a non-empty sub-array $a[i..j]$ of maximum sum. What is the maximum sum for $a=[-2,1,-3,4,-1,2,1,-5,4]$?
$6$
$4$
$7$
$12$
Explanation. $a[4..7]=[4,-1,2,1]$ has sum $6$. $7=4+2+1$ skips the $-1$, but a sub-array is made of consecutive elements; $12$ adds all the positives.
In the maximum-subarray problem (non-empty sub-array of consecutive elements), what is the solution if all elements are negative, for instance $a=[-5,-2,-8]$?
The empty sub-array, with sum $0$
The whole array, $[-5,-2,-8]$
The single largest element, $[-2]$
The problem has no solution
Explanation. Adding a negative element lowers the sum, so a single element, the least negative, is best. The empty sub-array is not allowed by the definition.
The brute-force algorithm for the maximum sub-array examines all index pairs $(i,j)$ with $1\le i\le j\le n$. How many pairs does it examine with $n=10$?
$55$
$45$
$100$
$10$
Explanation. The pairs with $i\le j$ are $\frac{n(n+1)}{2}=55$: the $45$ with $i<j$ plus the $10$ with $i=j$ (one-element sub-arrays).
Brute force for the maximum sub-array, for each $i$, updates the sum of $a[i..j]$ by adding $a[j]$ as $j$ grows, and performs $\Theta(n^2)$ steps. How many would it perform recomputing every sum from scratch?
$\Theta(n^2)$
$\Theta(n^3)$
$\Theta(n^2\log n)$
$\Theta(2^n)$
Explanation. There are $\Theta(n^2)$ pairs and adding up $a[i..j]$ from scratch costs $j-i+1$ steps: $\sum_{i\le j}(j-i+1)=\Theta(n^3)$ in all. The incremental update removes a factor $n$.
FindMaximumSubarray$(a,l,r)$ splits $a[l..r]$ at the midpoint $mid$ and calls itself on the two halves. Which sub-arrays are NOT considered by the two recursive calls?
Those made of a single element
Those ending at the last element $a[r]$
Those that have negative sum
Those containing $a[mid]$ and $a[mid+1]$
Explanation. The calls see only sub-arrays entirely in $a[l..mid]$ or entirely in $a[mid+1..r]$. Those crossing the midpoint are found by FindMaxCrossingSubarray, in linear time.
FindMaximumSubarray returns the best of three candidates: the maximum in the left half, the one in the right half and the one crossing the midpoint. Why are the three candidates enough?
Because the maximum sum is always in the left half
Because crossing sub-arrays have zero sum
Every sub-array lies left, right, or across the middle
Because every sub-array has at most three elements
Explanation. A sub-array $a[i..j]$ with $i\le mid<j$ crosses the midpoint; otherwise $j\le mid$ or $i>mid$. By the inductive hypothesis the calls are correct, and the Lemma gives the best crossing one.
FindMaximumSubarray makes two calls on the halves and one linear scan for the sub-array crossing the midpoint, so $T(n)=2T(n/2)+\Theta(n)$. What is its worst-case running time?
$\Theta(n\log n)$
$\Theta(n)$
$\Theta(n^2)$
$\Theta(\log n)$
Explanation. It is Merge Sort's recurrence: case 2 of the Master theorem. Better than brute force ($\Theta(n^2)$), worse than Kadane's algorithm ($\Theta(n)$).
FindMaxCrossingSubarray$(a,l,mid,r)$ looks for the maximum-sum sub-array containing $a[mid]$ and $a[mid+1]$: it scans from $mid$ towards $l$ for the best left sum, and from $mid+1$ towards $r$ for the best right sum. How much does it cost, with $n=r-l+1$?
$\Theta(n^2)$: all pairs are tried
$\Theta(\log n)$: the interval is halved
$\Theta(n)$: each element of $a[l..r]$ is examined once
$\Theta(1)$: only $a[mid]$ and $a[mid+1]$ are looked at
Explanation. The two parts are independent: the best left part (ending at $mid$) and the best right part (starting at $mid+1$) are added. Two scans, of $mid-l+1$ and $r-mid$ steps.
Kadane's algorithm scans $a$ keeping $cur$, the maximum sum of a sub-array ending at the current position ($cur\leftarrow\max(a[i],\,cur+a[i])$), and $best$, the maximum of the values of $cur$. What does it return on $a=[2,-5,3,1,-2,4]$?
$6$
$4$
$10$
$3$
Explanation. $cur$ takes $2,-3,3,4,2,6$: at $i=3$ it is better to restart from $3$ than $-3+3=0$. $best=6$, given by $[3,1,-2,4]$; $10$ adds only the positives.
RecursiveBinarySearch is correct on sorted arrays. What can be said if it is run on an UNSORTED array?
It always returns $-1$, for every value of $m$
Indices are right, but $-1$ may be wrong
The recursion never ends, because $mid$ repeats
It always returns a right index, or a right $-1$
Explanation. $mid$ is returned only after seeing $a[mid]=m$, so an index is always right; but discarding a half may remove $m$ (on $[5,1,4,2,3]$ with $m=1$ one gets $-1$). The interval shrinks anyway, so it terminates.
Kadane's algorithm looks for a NON-empty maximum-sum sub-array, with $best$ initialised to $a[1]$. A variant initialises $best:=0$ (as if the empty sub-array were allowed). What does it return on $a=[-5,-2,-8]$?
$0$
$-2$
$-15$
$-5$
Explanation. No sum exceeds $0$, so $best$ stays $0$, which is the sum of no non-empty sub-array ($-2$ is Kadane's answer). The variant solves a different problem (possibly empty sub-array): it differs only when all elements are negative.
MergeSortBottomUp starts from $width=1$ and, while $width<n$, merges the adjacent blocks of $width$ elements (one pass), then doubles $width$. How many passes does it execute on an array of $n=10$ elements?
$3$
$5$
$10$
$4$
Explanation. $width$ takes the values $1,2,4,8$, i.e., $\lceil\log_2 10\rceil=4$ passes; each costs $\bigO(n)$, for a total $\Theta(n\log_2 n)$ without the call stack.
PowerIt$(x,n)$ computes $x^n$ with $p:=1$, $y:=x$, $k:=n$ and, while $k>0$: if $k$ is odd $p\leftarrow p\cdot y$; then $y\leftarrow y\cdot y$ and $k\leftarrow\lfloor k/2\rfloor$. How many iterations does PowerIt$(x,100)$ execute?
$6$
$7$
$8$
$100$
Explanation. Each iteration replaces $k$ with $\lfloor k/2\rfloor$, i.e., removes one binary digit: the iterations are the binary digits of $100$, $\lfloor\log_2 100\rfloor+1=7$.
For $F(n)$: FibRec uses the recursion $F(n)=F(n-1)+F(n-2)$; FibMemo is the same recursion with a table $memo[0..n]$ of the values already computed; FibIt is a loop keeping only the last two values. Which statement is correct?
FibMemo and FibIt both use $\Theta(1)$ extra memory.
FibRec, FibMemo and FibIt all execute $\Theta(n)$ steps.
FibMemo executes an exponential number of calls, like FibRec.
FibMemo executes $\Theta(n)$ steps with $\Theta(n)$ memory; FibIt executes $\Theta(n)$ steps with $\Theta(1)$ extra memory.
Explanation. Memoization computes each value once ($2n-1$ calls) but uses the table and the stack; FibIt keeps only $prev$ and $curr$. FibRec executes $\Theta(\varphi^n)$ steps.
On an input of size $n$, the tree of calls of a recursive algorithm has one node per call and one child for each call made by that node. What is the recursion depth $D(n)$?
The total number of calls executed, i.e., the number of nodes of the tree.
The number of leaves of the tree of calls.
The maximum number of calls active at the same time, i.e., the height of the tree of calls plus one.
The number of recursive calls made directly by the first call.
Explanation. Definition 18.7: the stack memory is $\Theta(D(n))$ if the stack frames have constant size, while the number of steps depends on the number of nodes.
Let $f$ be tail recursive, with calls of constant cost and frames of constant size, with recursion depth $D(n)$, and let $g$ be the iterative algorithm obtained by replacing the final call with a loop on the new parameters. Which statement is correct?
$g$ gives the same result with steps of the same order, but uses $\Theta(1)$ memory instead of $\Theta(D(n))$.
$g$ executes asymptotically fewer steps than $f$, for instance $\Theta(\log n)$ instead of $\Theta(n)$.
$g$ uses the same memory as $f$, since the loop keeps all parameter values, but executes fewer steps.
$g$ is obtained this way from every recursive algorithm, also with two calls such as Fib, with the same gain.
Explanation. The loop goes through the same parameter values as the successive calls: the gain is only in the stack memory. Fib is not tail recursive.
We compare recursive and iterative algorithms for the same problem (sum of an array, sorting, power), with calls of constant cost. Which statement is correct?
A recursive algorithm is always asymptotically faster than its iterative version, thanks to the stack.
The gain comes from dividing the problem, not from recursion: decrease by one and the loop have the same order.
A recursive algorithm is always asymptotically slower than its iterative version, because of the cost of the calls.
Every divide and conquer algorithm executes $\Theta(n\log n)$ steps, whatever the cost of dividing and merging.
Explanation. RecursiveSumLinear and the loop both execute $\Theta(n)$ steps; Merge Sort beats Insertion Sort because it divides the problem, and MergeSortBottomUp gets the same $\Theta(n\log_2 n)$ without recursion.
FibMemo$(k,memo)$ returns $k$ if $k\le 1$; otherwise, if $memo[k]$ is undefined, it sets $memo[k]\leftarrow$FibMemo$(k-1)+$FibMemo$(k-2)$; it returns $memo[k]$. How do we prove that, with $memo$ all undefined and $n\ge 2$, it executes $2n-1$ calls?
$M(k)=M(k-1)+M(k-2)+1$, as for the recursion without table, and then $M(n)=2n-1$ by induction.
With the Master Theorem applied to $M(n)=2M(n/2)+1$, which gives $\Theta(n)$ calls.
$M(k)=M(k-1)+1$: the table avoids the second call entirely, except in the two base cases.
$M(2)=3$ and $M(k)=M(k-1)+2$: the second call finds $memo[k-2]$ already defined or is a base case.
Explanation. The first call fills $memo[2..k-1]$, the second returns immediately: hence $M(k)=M(k-1)+2$ and $M(n)=3+2(n-2)=2n-1$. $C(n)=C(n-1)+C(n-2)+1$ counts the calls of FibRec.
At each function call the computer creates a record (stack frame) on the call stack. What does it contain, and when is it removed?
Only the returned value; it is removed as soon as the next recursive call starts.
The code of the called function; it is removed at the end of the whole program.
Parameters and local variables; it is removed when the call makes another one.
Parameters, local variables and return address; it is removed when the call terminates.
Explanation. All the calls that have started and not yet terminated keep their record on the stack: this is why the memory used is proportional to the depth of the recursion.
SumDecrease$(a,n)$ returns SumDecrease$(a,n-1)+a[n]$ (with SumDecrease$(a,0)=0$), so its depth of recursion is $n+1$. With records of $32$ bytes and a stack of $8$ MB $=8\cdot 2^{20}$ bytes, what is approximately the largest $n$ that does not cause a stack overflow?
About $8\cdot 10^6$
About $2.6\cdot 10^5$
About $2.6\cdot 10^8$
About $23$
Explanation. $8\cdot 2^{20}/32=262\,144$ records: beyond that the stack overflows, although the array would easily fit in memory. The halving version has depth $\Theta(\log_2 n)$ and does not have this problem.
The best iterative algorithm of the course is compared with the recursive one for the same problem. For which problem is the recursive version asymptotically faster?
The sum of an array: halving recursion performs $\Theta(\log_2 n)$ steps against $\Theta(n)$
Binary search: the recursive version performs $\Theta(1)$ steps against $\Theta(\log_2 n)$
Sorting: MergeSort $\Theta(n\log_2 n)$ against $\Theta(n^2)$ of Insertion, Selection and Exchange Sort
The Fibonacci numbers: recursion performs $\Theta(\log_2 n)$ steps against $\Theta(n)$ of the loop
Explanation. Only for sorting does divide and conquer give a better order (paid with $\Theta(n)$ memory). The sum stays $\Theta(n)$, binary search $\Theta(\log_2 n)$, and recursive Fib is exponential.
For the maximum subarray problem one compares brute force (all pairs $l\le r$), the divide and conquer FindMaximumSubarray and Kadane's iterative algorithm (one scan). Which conclusion is correct?
Divide and conquer ($\Theta(n\log_2 n)$) beats brute force ($\Theta(n^2)$), but Kadane ($\Theta(n)$ time, $\Theta(1)$ memory) beats both.
Divide and conquer ($\Theta(n\log_2 n)$) is the best of the three, because recursion is always faster than a loop on the same problem.
Brute force and divide and conquer have the same order $\Theta(n^2)$; only Kadane, with $\Theta(n)$ time, really improves the situation.
Kadane is $\Theta(n\log_2 n)$ like divide and conquer, but it uses less memory, because it has no stack of recursive calls.
Explanation. A recursive algorithm can improve on brute force and still be beaten by a smarter loop: it must always be compared with the best iterative algorithm.
In an experiment random arrays of $n=10^4$ and then of $n=10^5$ elements are sorted with InsertionSort ($\Theta(n^2)$) and MergeSort ($\Theta(n\log_2 n)$). By which factors are the two running times multiplied, according to the theory?
About $10$ and about $10$
About $100$ and about $100$
About $100$ and about $12.5$
About $100$ and about $10$
Explanation. $(10^5/10^4)^2=100$; for MergeSort $10\cdot\frac{\log_2 10^5}{\log_2 10^4}=10\cdot\frac54=12.5$. In the experiment of the notes the measured factors are about $98$ and $12$.
The running time of the naive recursive function for the Fibonacci numbers is proportional to the number of calls, which grows as $\varphi^n$ with $\varphi=\frac{1+\sqrt5}{2}\approx 1.618$. By which factor is the time approximately multiplied when $n$ increases by $5$?
About $11$
About $5$
About $32$
About $25$
Explanation. $\varphi^5\approx 11.09$. $2^5=32$ would use base $2$ instead of $\varphi$; $5$ and $25$ would correspond to linear or quadratic growth. In a semi-logarithmic plot the curve is a straight line.
According to the guidelines on the use of recursion, in which situation should it be avoided?
When the problem splits into a few independent subproblems of size $n/b$, as for MergeSort.
When the problem decreases from $n$ to $n-1$ with constant work, as for the factorial or linear search.
When the depth of the recursion is small, typically $\Theta(\log_2 n)$, as for FastPower.
When the recursive description is the natural one and no gain is possible, as for Hanoi.
Explanation. Decrease by one is a loop in disguise: same time, call overhead, $\Theta(n)$ stack memory and risk of stack overflow. The other three are the cases in which the guidelines recommend recursion.
A naive recursive algorithm solves the same subproblems many times (overlapping subproblems, as for the Fibonacci numbers). What do the guidelines recommend?
Rewriting the algorithm in tail-recursive form, which removes the repeated calls.
Increasing the size of the call stack, to avoid the stack overflow.
Applying the Master Theorem to choose the optimal size of the subproblems.
Memoization or, better, a bottom-up loop (Dynamic Programming).
Explanation. With a table of the values already computed, or by computing them bottom-up, every subproblem is solved only once: for Fibonacci one goes from an exponential number of steps to $\Theta(n)$.
FibRec$(n)$ returns $n$ if $n \le 1$, otherwise FibRec$(n-1)+$FibRec$(n-2)$. The number of calls is $C(n)=2F(n+1)-1$, with $F$ the Fibonacci numbers ($F(0)=0$, $F(1)=1$). How many calls does FibRec$(5)$ make?
$15$
$8$
$9$
$31$
Explanation. $F(6)=8$, so $C(5)=2 \cdot 8-1=15$. $8$ is $F(6)$ without the factor $2$; $31=2^5-1$ would be a complete tree.
Let $\varphi=(1+\sqrt5)/2 \approx 1.618$. Which statement about the growth of the Fibonacci numbers and the cost of FibRec is correct?
$F(n)=\Theta(n^2)$, so FibRec is quadratic
$\varphi^{n-2} \le F(n) \le \varphi^{n-1}$, so FibRec takes $\Theta(\varphi^n)$ steps: exponential time
$F(n)=\Theta(2^n)$ exactly
FibRec is linear since it makes one addition per call
Explanation. The number of calls is $2F(n+1)-1=\Theta(\varphi^n)$, and every call costs a constant. The iterative version computes $F(n)$ in $\Theta(n)$ steps.
A recursive call is a tail call if it is the last operation of the function and its result is returned as it is. Which function is tail recursive?
Factorial$(n)$: it returns $n \cdot$Factorial$(n-1)$
Fib$(n)$: it returns Fib$(n-1)+$Fib$(n-2)$
RecursiveSum: it returns the sum of the two calls on the halves
RecursiveGCD$(n,m)$: if $m=0$ it returns $n$, otherwise it returns RecursiveGCD$(m,n \bmod m)$
Explanation. In GCD the result of the call is returned with no further operation; in Factorial the multiplication by $n$ remains, in Fib and RecursiveSum the addition.
SumDecrease$(a,n)$ returns SumDecrease$(a,n-1)+a[n]$ (base case $n=0$), so it keeps $n+1$ calls active together. With $n=10^7$ and about $32$ bytes per stack frame, how much stack memory would be needed?
About $32$ bytes
About $40$ MB
About $8$ MB
About $320$ MB
Explanation. $10^7\cdot 32$ bytes $=3.2\cdot 10^8$ bytes: far more than the typical $8$ MB stack, so the program crashes (stack overflow). $40$ MB is the array itself, which fits easily in memory.
At each call the computer creates a stack frame (parameters, local variables, return address), removed only when the call ends. Which is NOT a hidden cost of recursion compared with a loop?
The time to create and remove frames
An asymptotically larger number of steps
The memory taken by the active frames
The risk of stack overflow
Explanation. For the same algorithm, recursion adds per-call costs (time), frames in memory and the stack limit; it does not change the order of growth of the steps, as SumDecrease and the loop show, both $\Theta(n)$.
The halving sum can be written without recursion using an explicit stack $P$ of pairs $(l,r)$: the top pair is popped and, if $l<r$, $(mid+1,r)$ and then $(l,mid)$ are pushed. With $a=[4,7,1,9]$, after popping $(1,4)$ and pushing $(3,4)$ and $(1,2)$, which pair is popped next?
$(3,4)$
$(1,1)$
$(1,4)$
$(1,2)$
Explanation. The stack returns first the last pair pushed: $(1,2)$. So the order of work is the same as in the recursion, which calls the left half first.
Every recursive algorithm can be turned into an iterative one by managing an explicit stack of the parameters of the calls still to run. For the halving sum on $n$ elements, how large does the explicit stack get at most?
$\Theta(1)$
$\Theta(\log n)$
$\Theta(n)$
$\Theta(n\log n)$
Explanation. The explicit stack does the job of the call stack: it holds the pending sub-arrays, at most a couple per level. One saves the cost of calls, not the memory.
SumDecrease$(a,n)$ (base case $n=0$; otherwise SumDecrease$(a,n-1)+a[n]$) has $S(n)=S(n-1)+c$ steps, like the loop that adds up $a[1..n]$. What advantage does the recursive version have?
None: if anything it costs more memory
It performs $\Theta(\log n)$ steps instead of $\Theta(n)$
It uses less memory, because it has no variable $i$
It can run in parallel on the two halves
Explanation. Both make $\Theta(n)$ steps, but the recursion uses $\Theta(n)$ frames (against $\Theta(1)$ variables) and pays for each call. Parallelism concerns splitting in half, not decreasing by one.
MergeSortBottomUp merges blocks of $1,2,4,\dots$ elements without any recursive call, and also performs $\Theta(n\log n)$ steps. What does it teach about the gain of Merge Sort over Insertion Sort?
It comes from recursive calls, which are faster than loops
It comes from Merge Sort being in-place
It comes from halving and merging in linear time, not from recursion
There is no gain: the two algorithms have the same order
Explanation. The iterative version has the same order of growth: what counts is the structure of $\log_2 n$ levels of linear merges. Recursion is just a convenient way to write it.
The iterative fast power PowerIt$(x,n)$ halves the residual exponent $k$ at each iteration ($k\leftarrow\lfloor k/2\rfloor$, starting from $k=n$, while $k>0$), multiplying $p$ by $y$ when $k$ is odd and then squaring $y$. For $n=13=(1101)_2$, how many times is the multiplication $p\leftarrow p\cdot y$ executed?
$4$
$3$
$13$
$2$
Explanation. $k$ takes $13,6,3,1$: it is odd for $13$, $3$ and $1$, that is once for each digit $1$ of the binary representation of $n$. There are $4$ iterations, one per digit.
For the maximum sub-array, the divide-and-conquer FindMaximumSubarray performs $\Theta(n\log n)$ steps with recursion depth $\Theta(\log n)$; Kadane's iterative algorithm performs $\Theta(n)$ steps with two variables. Which statement is correct?
Divide and conquer is better in time
They are equivalent: both $\Theta(n\log n)$
Kadane is faster but uses $\Theta(n)$ memory
Kadane is better both in time and in memory
Explanation. $\Theta(n)$ steps and $\Theta(1)$ memory against $\Theta(n\log n)$ steps and $\Theta(\log n)$ frames. Here a different idea (extending the best sum ending at $i$) beats halving.
On an array of $n=2^{20}\approx 10^6$ elements, FindMaximumSubarray performs about $n\log_2 n$ steps and Kadane about $n$ (ignoring constants). By about what factor is divide and conquer slower?
About $10^6$
About $20$
About $2$
About $1000$
Explanation. $\frac{n\log_2 n}{n}=\log_2 n=20$. The gap between $\Theta(n\log n)$ and $\Theta(n)$ grows only like $\log n$, much more slowly than that between $\Theta(n^2)$ and $\Theta(n)$ ($10^6$).
To multiply two $n$-digit integers one splits them into halves of $n/2$ digits. With four products of halves the recurrence is $S(n)=4S(n/2)+\Theta(n)$; Karatsuba uses three, $S(n)=3S(n/2)+\Theta(n)$. What are the solutions?
$\Theta(n\log n)$ in both cases
$\Theta(n^2)$ in both cases
$\Theta(n^4)$ and $\Theta(n^3)$
$\Theta(n^2)$ and $\Theta(n^{\log_2 3})$
Explanation. Case 1 of the Master theorem: $n^{\log_2 4}=n^2$ and $n^{\log_2 3}\approx n^{1.585}$ dominate $f(n)=\Theta(n)$. With four products nothing is gained over the schoolbook method; saving one lowers the exponent.
For numbers of $n=1024=2^{10}$ digits, one compares $n^2$ (schoolbook method) and $n^{\log_2 3}=3^{10}$ (Karatsuba), ignoring constants. By about what factor is Karatsuba faster?
About $18$
About $1.5$
About $1000$
About $3$
Explanation. $n^2=2^{20}\approx 1.05\cdot 10^6$ and $3^{10}=59049$: ratio $(4/3)^{10}\approx 17.8$. The advantage grows with $n$, like $n^{2-\log_2 3}\approx n^{0.415}$.
FibMemo$(k,memo)$ computes Fibonacci numbers with the same recursion as FibRec, but uses a table $memo$. What does $memo[k]$ contain, and when is it used?
The number of calls made with argument $k$
The return address of the call on $k$
The value $F(k)$, stored the first time and then read back
The value $F(k-1)+F(k-2)$, recomputed at every call
Explanation. The first call on $k$ computes $F(k)$ and stores it; later ones read it with no new calls. So each subproblem is solved only once, and the calls become $\Theta(n)$.
To compute $F(n)$, FibMemo uses a table $memo[0..n]$ and a recursion of depth $\Theta(n)$; the iterative algorithm keeps only the last two values. How much extra memory do they use?
$\Theta(n)$ and $\Theta(1)$
$\Theta(1)$ and $\Theta(1)$
$\Theta(n)$ and $\Theta(n)$
$\Theta(2^n)$ and $\Theta(n)$
Explanation. FibMemo's table and call stack are both $\Theta(n)$; the loop uses a fixed number of variables. The steps are $\Theta(n)$ in both cases.
The recursion depth is the largest number of calls active together. FibRec$(n)$ returns $n$ if $n\le 1$, otherwise FibRec$(n-1)+$FibRec$(n-2)$. What is its depth, for $n\ge 1$?
$2^n$
$\log_2 n$
$n$
$F(n)$
Explanation. The longest path in the tree is FibRec$(n)\to(n-1)\to\dots\to(1)$: $n$ calls. The calls in all are exponentially many, but the stack memory is only $\Theta(n)$.
In the chapter's experiment each time measurement is repeated until at least $0.2$ seconds have passed (and at least $3$ repetitions), reporting the average time. Why?
To warm up the processor before measuring
Because every algorithm must last $0.2$ seconds
To limit the memory used by the stack
To measure accurately even very short computations
Explanation. A computation of a few microseconds is shorter than the clock resolution: repeating it many times and dividing makes the measurement error negligible.
In the experiment the random arrays are generated with a fixed seed ($12345$). What is it for?
To make the arrays already sorted
To make the experiment repeatable, with the same data
To choose the worst case of each algorithm
To reduce the time needed to generate the arrays
Explanation. With the same seed the generator always produces the same sequence: whoever repeats the experiment, and every algorithm compared, works on the same arrays.
In the sorting experiment the recursive mergeSort and mergeSortBottomUp (iterative) have very similar times, while insertionSort is much slower for large $n$. What is the conclusion?
The order of growth matters, not recursion
Recursion makes Merge Sort faster
Insertion Sort is slow because it is iterative
The times do not depend on the algorithm used
Explanation. $\Theta(n\log n)$ against $\Theta(n^2)$ makes the difference; between the two versions of Merge Sort, with the same order, the call overhead weighs little.
Ignoring constants, for $n=10^5$ Insertion Sort performs about $n^2$ steps and Merge Sort about $n\log_2 n$ (with $\log_2 10^5\approx 17$). By about what factor is Merge Sort faster?
About $17$
About $10^5$
About $6000$
About $10$
Explanation. $\frac{n^2}{n\log_2 n}=\frac{n}{\log_2 n}\approx\frac{10^5}{17}\approx 5900$. The ratio grows almost linearly with $n$.
In the experiment the calls of fibonacciRec$(n)$ are $2F(n+1)-1$ ($F$: Fibonacci numbers, $F(21)=10946$). How many calls does fibonacciRec$(20)$ make?
$21891$
$10946$
$20$
$39$
Explanation. $2\cdot 10946-1=21891$: already for $n=20$ tens of thousands of calls, against the $20$ iterations of fibonacciIt. $39=2n-1$ would be with memoisation.
In the experiment fibonacciIt is measured by repeating it in blocks of $10^5$ calls, fibonacciRec is not. Why?
Because fibonacciIt gives different results at each call
Because fibonacciIt uses a lot of memory
One call of fibonacciIt is too short to be measured alone
Because fibonacciRec is faster
Explanation. fibonacciIt performs $\Theta(n)$ steps, a few dozen for $n\le 40$: nanoseconds. fibonacciRec for $n=40$ makes hundreds of millions of calls and takes seconds.
With the default $8$ MB stack, sumRecDecrease (decrease by one) crashes for $n=10^6$, while sumRecHalving (halving) never crashes up to $n=10^7$. Why?
sumRecHalving performs fewer steps
sumRecHalving has at most $\lceil\log_2 n\rceil+1\le 25$ active frames
sumRecHalving does not use the call stack
sumRecDecrease has a mistake in its base case
Explanation. Both versions make $\Theta(n)$ steps, but the depth is $n+1$ against $\Theta(\log n)$: a million frames do not fit in $8$ MB, $25$ frames do.
In the sum experiment, sumIt, sumRecHalving and sumRecDecrease have the same order $\Theta(n)$: multiplying $n$ by $10$, times grow by about $10$. The recursive versions, however, are slower by a factor $3$–$13$. How is this interpreted?
The recursive versions have a larger order of growth
It is a measurement error, to be ignored
The recursive versions are slower only for small $n$
It is the constant cost of calls, which does not change the order
Explanation. A constant factor independent of $n$ does not change the class $\Theta(n)$, but it matters in practice: this is why a loop is preferred when recursion brings no advantage.
According to the chapter's guidelines, in which situation is recursion the natural choice?
A problem reducing to $n-1$ with very large $n$
Divide and conquer with subproblems of size $n/b$
Repeated subproblems, without memoisation
When constant extra memory is required
Explanation. With fractional-size subproblems the depth is $\Theta(\log n)$ and recursive code follows the structure of the problem (Merge Sort, Karatsuba). In the other cases a loop or memoisation is preferable.
An algorithm is tail recursive, but the language used does not eliminate tail calls, and the recursion depth can reach $10^6$. What should be done?
Add a second base case
Split the recursion into two calls on half the input
Nothing: tail recursion does not use the stack
Rewrite it as a while loop that updates the parameters
Explanation. Without automatic elimination each call still takes a frame, and a million frames risk a stack overflow. The transformation into a loop is immediate precisely because the call is in tail position.
A tail-recursive algorithm turns into a loop with $\Theta(1)$ memory. Does this also hold for Factorial$(n)=n\cdot$Factorial$(n-1)$ as written?
Yes: the call is the last line of the function
Yes, because it has a single base case
No, because the result is not an integer
No: after the call the multiplication by $n$ remains
Explanation. Tail position means that the result of the call is returned unchanged. Here it still has to be multiplied, so the caller's frame stays on the stack; with an accumulator, Factorial$(n,acc)$ becomes tail recursive.
Generated questions (53)
Each generator builds a new instance, with different numbers, at every start: a few examples here.
Which natural number, in base ten, is represented by the sequence of digits $(1100100)_2$?
$200$
$19$
$100$
$116$
Explanation. The digit in position $i$ (counted from the right, starting at $0$) contributes $d_i\,2^i$: $2^{6}+2^{5}+2^{2}=100$. Reading the digits in reverse order or counting the positions from $1$ (twice the value) are the typical mistakes.
Which natural number, in base ten, is represented by the sequence of digits $(1110101)_2$?
$113$
$234$
$87$
$117$
Explanation. The digit in position $i$ (counted from the right, starting at $0$) contributes $d_i\,2^i$: $2^{6}+2^{5}+2^{4}+2^{2}+2^{0}=117$. Reading the digits in reverse order or counting the positions from $1$ (twice the value) are the typical mistakes.
The sequence of $8$ bits $(11100100)_2$ is the two's complement representation of an integer. Which one?
$-100$
$228$
$-28$
$-27$
Explanation. The most significant bit is $1$: the integer is negative and equals $r-2^k=228-256=-28$, where $r=228$ is the natural value of the sequence.
What is the minimum number of bits needed to represent the integer $-172$ in two's complement?
$8$
$9$
$10$
$11$
Explanation. We need the smallest $k$ with $-2^{k-1}\le -172\le 2^{k-1}-1$: $k=9$ ($\lceil\log_2|n|\rceil+1$). The value $\lfloor\log_2|n|\rfloor+1$ forgets the sign bit.
What is the minimum number of bits needed to represent the integer $-116$ in two's complement?
$10$
$9$
$8$
$7$
Explanation. We need the smallest $k$ with $-2^{k-1}\le -116\le 2^{k-1}-1$: $k=8$ ($\lceil\log_2|n|\rceil+1$). The value $\lfloor\log_2|n|\rfloor+1$ forgets the sign bit.
With $8$ bits in two's complement, $(10100001)_2$ and $(01001010)_2$ are added as natural numbers, keeping the $8$ least significant bits. Which integer does the result represent, and is there an overflow?
result $-21$, no overflow
result $21$, no overflow
result $-21$, overflow
result $235$, no overflow
Explanation. The operands are $-95$ and $74$, the true sum is $-21$; the $8$ bits of the result are $(11101011)_2$, i.e., $-21$. No overflow: $-21\in[-128,127]$.
With $8$ bits in two's complement, $(10111111)_2$ and $(11010001)_2$ are added as natural numbers, keeping the $8$ least significant bits. Which integer does the result represent, and is there an overflow?
result $-112$, no overflow
result $112$, no overflow
result $144$, no overflow
result $-112$, overflow
Explanation. The operands are $-65$ and $-47$, the true sum is $-112$; the $8$ bits of the result are $(10010000)_2$, i.e., $-112$. No overflow: $-112\in[-128,127]$.
Which sequence of digits in base $2$ represents the natural number $158$ (written in base ten)?
$(10011110)_2$
$(01111001)_2$
$(10011101)_2$
$(10011111)_2$
Explanation. Dividing repeatedly by $2$, the remainders read from the last to the first give $(10011110)_2$; reading them in the order they come out gives the reversed sequence $(01111001)_2$.
Which sequence of digits in base $2$ represents the natural number $118$ (written in base ten)?
$(0110111)_2$
$(1110111)_2$
$(1110110)_2$
$(1110101)_2$
Explanation. Dividing repeatedly by $2$, the remainders read from the last to the first give $(1110110)_2$; reading them in the order they come out gives the reversed sequence $(0110111)_2$.
In sign-magnitude representation with $k=8$ bits the most significant bit is the sign ($0$ for $n \ge 0$, $1$ for $n<0$) and the other $7$ bits are the magnitude $|n|$ in binary. How is $n=-70$ represented?
$11000110$
$10111010$
$01000110$
$10111001$
Explanation. Sign $1$ and magnitude $70=(1000110)_2$ on $7$ bits: $11000110$. $10111010$ is the two's complement representation ($2^8-70$), $01000110$ that of $+70$.
In sign-magnitude representation with $k=8$ bits the most significant bit is the sign ($0$ for $n \ge 0$, $1$ for $n<0$) and the other $7$ bits are the magnitude $|n|$ in binary. How is $n=-48$ represented?
$11010000$
$11001111$
$10110000$
$00110000$
Explanation. Sign $1$ and magnitude $48=(0110000)_2$ on $7$ bits: $10110000$. $11010000$ is the two's complement representation ($2^8-48$), $00110000$ that of $+48$.
2. Pseudo-code (2)
Example 1 · alg-g-trace-loop · level facile · notes
What is the value of the variable $c$ at the end of the following pseudo-code?
<pre>x := 124
c := 0
<b>while</b> x > 1 <b>do</b>
x ← ⌊x / 2⌋
c ← c + 1
<b>end</b></pre>
$7$
$6$
$5$
$8$
Explanation. Each iteration halves $x$ (rounding down): $x$ reaches $1$ after $\lfloor\log_2 124\rfloor=6$ iterations, hence $c=6$.
Example 2 · alg-g-trace-loop · level facile · notes
What is the value of the variable $c$ at the end of the following pseudo-code?
<pre>x := 172
c := 0
<b>while</b> x > 1 <b>do</b>
x ← ⌊x / 2⌋
c ← c + 1
<b>end</b></pre>
$9$
$6$
$7$
$8$
Explanation. Each iteration halves $x$ (rounding down): $x$ reaches $1$ after $\lfloor\log_2 172\rfloor=7$ iterations, hence $c=7$.
Example 1 · alg-g-collatz · level complessa · notes
What are the values of $k$ and $y$ at the end of the following pseudo-code?
<pre>x := 26
y := 0
k := 0
<b>while</b> x ≠ 1 <b>do</b>
<b>if</b> x mod 2 = 0 <b>then</b>
x ← x / 2
<b>else</b>
x ← 3x + 1
<b>end</b>
k ← k + 1
<b>if</b> x > y <b>then</b>
y ← x
<b>end</b>
<b>end</b></pre>
$k=11$, $y=40$
$k=10$, $y=40$
$k=9$, $y=40$
$k=10$, $y=20$
Explanation. The values of $x$ are $26,\ 13,\ 40,\ 20,\ 10,\ 5,\ 16,\ 8,\ 4,\ 2,\ 1$: there are $k=10$ iterations and the largest value assigned to $x$ in the loop (the initial value does not count, since $y$ is updated after $x$ changes) is $y=40$.
Example 2 · alg-g-collatz · level complessa · notes
What are the values of $k$ and $y$ at the end of the following pseudo-code?
<pre>x := 19
y := 0
k := 0
<b>while</b> x ≠ 1 <b>do</b>
<b>if</b> x mod 2 = 0 <b>then</b>
x ← x / 2
<b>else</b>
x ← 3x + 1
<b>end</b>
k ← k + 1
<b>if</b> x > y <b>then</b>
y ← x
<b>end</b>
<b>end</b></pre>
$k=21$, $y=88$
$k=19$, $y=88$
$k=20$, $y=88$
$k=20$, $y=58$
Explanation. The values of $x$ are $19,\ 58,\ 29,\ 88,\ 44,\ 22,\ 11,\ 34,\ 17,\ 52,\ 26,\ 13,\ 40,\ 20,\ 10,\ 5,\ 16,\ 8,\ 4,\ 2,\ 1$: there are $k=20$ iterations and the largest value assigned to $x$ in the loop (the initial value does not count, since $y$ is updated after $x$ changes) is $y=88$.
3. Sorting algorithms (5)
Example 1 · alg-g-insertion-pass · level facile · notes
InsertionSort sorts $a[1..n]$ in increasing order: for $i=2,\dots,n$ it inserts $\mathit{key}=a[i]$ into the prefix $a[1..i-1]$, shifting one place to the right the keys larger than $\mathit{key}$. It is executed on $a=[3, 6, 4, 5, 9, 7]$. What does the array contain at the end of the iteration with $i=3$?
$[3, 4, 6, 5, 9, 7]$
$[3, 4, 5, 6, 9, 7]$
$[3, 4, 5, 6, 7, 9]$
$[3, 6, 4, 5, 9, 7]$
Explanation. After the iterations $i=2,\dots,3$ the sub-array $a[1..3]$ contains the first $3$ elements sorted, and the rest is unchanged: $[3, 4, 6, 5, 9, 7]$.
Example 2 · alg-g-insertion-pass · level facile · notes
InsertionSort sorts $a[1..n]$ in increasing order: for $i=2,\dots,n$ it inserts $\mathit{key}=a[i]$ into the prefix $a[1..i-1]$, shifting one place to the right the keys larger than $\mathit{key}$. It is executed on $a=[7, 9, 5, 2, 8, 1]$. What does the array contain at the end of the iteration with $i=4$?
$[2, 5, 7, 8, 9, 1]$
$[5, 7, 9, 2, 8, 1]$
$[2, 5, 7, 9, 8, 1]$
$[1, 2, 5, 9, 8, 7]$
Explanation. After the iterations $i=2,\dots,4$ the sub-array $a[1..4]$ contains the first $4$ elements sorted, and the rest is unchanged: $[2, 5, 7, 9, 8, 1]$.
Example 1 · alg-g-selection-pass · level facile · notes
SelectionSort sorts $a[1..n]$ in increasing order: for $i=1,\dots,n-1$ it finds the position of the minimum of $a[i..n]$ and swaps it with $a[i]$. It is executed on $a=[2, 5, 3, 7, 8, 1]$. What does the array contain after the first $2$ iterations ($i=1,\dots,2$)?
$[2, 3, 5, 7, 8, 1]$
$[1, 2, 5, 7, 8, 3]$
$[1, 5, 3, 7, 8, 2]$
$[1, 2, 3, 7, 8, 5]$
Explanation. In each iteration the minimum of $a[i..n]$ is swapped with $a[i]$ (one swap per iteration): $[1, 2, 3, 7, 8, 5]$. Exchange Sort, instead, swaps every time it finds an element smaller than $a[i]$.
Example 2 · alg-g-selection-pass · level facile · notes
SelectionSort sorts $a[1..n]$ in increasing order: for $i=1,\dots,n-1$ it finds the position of the minimum of $a[i..n]$ and swaps it with $a[i]$. It is executed on $a=[6, 5, 8, 9, 2, 1]$. What does the array contain after the first $3$ iterations ($i=1,\dots,3$)?
$[1, 2, 5, 9, 8, 6]$
$[1, 2, 8, 9, 5, 6]$
$[5, 6, 8, 9, 2, 1]$
$[1, 2, 5, 6, 8, 9]$
Explanation. In each iteration the minimum of $a[i..n]$ is swapped with $a[i]$ (one swap per iteration): $[1, 2, 5, 9, 8, 6]$. Exchange Sort, instead, swaps every time it finds an element smaller than $a[i]$.
Example 1 · alg-g-exchange-pass · level facile · notes
ExchangeSort sorts $a[1..n]$ in increasing order: for $i=1,\dots,n-1$ and, inside, for $j=i+1,\dots,n$, it swaps $a[i]$ and $a[j]$ if $a[i]>a[j]$. It is executed on $a=[8, 3, 2, 4, 1, 7]$. What does the array contain at the end of the first two iterations of the outer loop ($i=1,2$)?
$[1, 2, 3, 4, 8, 7]$
$[1, 2, 3, 8, 4, 7]$
$[8, 7, 2, 3, 1, 4]$
$[1, 2, 8, 4, 3, 7]$
Explanation. For every $j>i$, if $a[i]>a[j]$ the two elements are swapped: at the end of the iteration $a[i]$ is the minimum of $a[i..n]$, but the other elements have moved as well: $[1, 2, 8, 4, 3, 7]$.
Example 2 · alg-g-exchange-pass · level facile · notes
ExchangeSort sorts $a[1..n]$ in increasing order: for $i=1,\dots,n-1$ and, inside, for $j=i+1,\dots,n$, it swaps $a[i]$ and $a[j]$ if $a[i]>a[j]$. It is executed on $a=[6, 5, 8, 9, 2, 1]$. What does the array contain at the end of the first two iterations of the outer loop ($i=1,2$)?
$[1, 2, 8, 9, 6, 5]$
$[9, 8, 5, 6, 2, 1]$
$[1, 2, 8, 9, 5, 6]$
$[1, 2, 5, 9, 8, 6]$
Explanation. For every $j>i$, if $a[i]>a[j]$ the two elements are swapped: at the end of the iteration $a[i]$ is the minimum of $a[i..n]$, but the other elements have moved as well: $[1, 2, 8, 9, 6, 5]$.
Example 1 · alg-g-insertion-counts · level media · notes
InsertionSort, for $i=2,\dots,n$, sets $\mathit{key}=a[i]$, $j=i-1$ and, while $j\ge 1$ and $a[j]>\mathit{key}$, shifts $a[j]$ into $a[j+1]$ and decrements $j$; then it writes $\mathit{key}$ into $a[j+1]$. How many comparisons $a[j]>\mathit{key}$ and how many shifts does it perform on the array $[8, 3, 2, 4, 1, 7]$?
$15$ comparisons, $9$ shifts
$9$ comparisons, $9$ shifts
$11$ comparisons, $9$ shifts
$10$ comparisons, $9$ shifts
Explanation. The shifts are the pairs in reverse order: $9$. Each iteration makes one comparison per shift, plus one false comparison that stops it unless it reaches $j=0$: $11$ comparisons in total.
Example 2 · alg-g-insertion-counts · level media · notes
InsertionSort, for $i=2,\dots,n$, sets $\mathit{key}=a[i]$, $j=i-1$ and, while $j\ge 1$ and $a[j]>\mathit{key}$, shifts $a[j]$ into $a[j+1]$ and decrements $j$; then it writes $\mathit{key}$ into $a[j+1]$. How many comparisons $a[j]>\mathit{key}$ and how many shifts does it perform on the array $[6, 5, 8, 9, 2, 1]$?
$12$ comparisons, $10$ shifts
$10$ comparisons, $10$ shifts
$15$ comparisons, $10$ shifts
$11$ comparisons, $10$ shifts
Explanation. The shifts are the pairs in reverse order: $10$. Each iteration makes one comparison per shift, plus one false comparison that stops it unless it reaches $j=0$: $12$ comparisons in total.
Example 1 · alg-g-selection-stability · level complessa · notes
SelectionSort sorts by key an array of records (key, letter): for $i=1,\dots,n-1$ it looks for the minimum of $a[i..n]$ with the strict comparison $a[j]<a[\mathit{minIdx}]$ (on ties the first one found wins) and swaps it with $a[i]$. What is the final array for $(2,A),\ (2,B),\ (3,C),\ (3,D),\ (1,E),\ (3,F)$?
$(1,E),\ (2,B),\ (2,A),\ (3,D),\ (3,C),\ (3,F)$
$(1,E),\ (2,B),\ (2,A),\ (3,F),\ (3,D),\ (3,C)$
$(1,E),\ (2,A),\ (2,B),\ (3,C),\ (3,D),\ (3,F)$
$(1,E),\ (2,A),\ (2,B),\ (3,F),\ (3,D),\ (3,C)$
Explanation. Following the $5$ iterations (minimum of $a[i..n]$ with the strict comparison $a[j]<a[\mathit{minIdx}]$, then one swap) we obtain $(1,E),\ (2,B),\ (2,A),\ (3,D),\ (3,C),\ (3,F)$. A swap can move a record past a record with the same key: Selection Sort is not stable, and the stable order (the one of Insertion Sort) is different.
Example 2 · alg-g-selection-stability · level complessa · notes
SelectionSort sorts by key an array of records (key, letter): for $i=1,\dots,n-1$ it looks for the minimum of $a[i..n]$ with the strict comparison $a[j]<a[\mathit{minIdx}]$ (on ties the first one found wins) and swaps it with $a[i]$. What is the final array for $(3,A),\ (2,B),\ (3,C),\ (3,D),\ (2,E),\ (3,F)$?
$(2,E),\ (2,B),\ (3,F),\ (3,C),\ (3,D),\ (3,A)$
$(2,B),\ (2,E),\ (3,A),\ (3,C),\ (3,D),\ (3,F)$
$(2,B),\ (2,E),\ (3,C),\ (3,D),\ (3,A),\ (3,F)$
$(2,E),\ (2,B),\ (3,F),\ (3,D),\ (3,C),\ (3,A)$
Explanation. Following the $5$ iterations (minimum of $a[i..n]$ with the strict comparison $a[j]<a[\mathit{minIdx}]$, then one swap) we obtain $(2,B),\ (2,E),\ (3,C),\ (3,D),\ (3,A),\ (3,F)$. A swap can move a record past a record with the same key: Selection Sort is not stable, and the stable order (the one of Insertion Sort) is different.
4. Linear and binary search (2)
Example 1 · alg-g-binsearch · level facile · notes
BinarySearch looks for $m=16$ in $a=[3, 8, 14, 16, 22, 27, 32, 38, 40, 46, 48, 51]$ (indices $1$ to $12$): it starts from $left=1$, $right=12$ and, while $left\le right$, examines $mid=left+\lfloor(right-left)/2\rfloor$, returns $mid$ if $a[mid]=m$, otherwise sets $left\leftarrow mid+1$ if $a[mid]<m$ and $right\leftarrow mid-1$ if $a[mid]>m$; at the end it returns $-1$. Which indices $mid$ does it examine, and what does it return?
$mid$: $7,\ 4$; returns $4$
$mid$: $6,\ 3$; returns $-1$
$mid$: $6,\ 3,\ 4$; returns $4$
$mid$: $6,\ 9,\ 11,\ 12$; returns $-1$
Explanation. With $mid=left+\lfloor(right-left)/2\rfloor$, if $a[mid]<m$ we set $left\leftarrow mid+1$, otherwise $right\leftarrow mid-1$: indices $6,\ 3,\ 4$, returned value $4$.
Example 2 · alg-g-binsearch · level facile · notes
BinarySearch looks for $m=51$ in $a=[5, 8, 10, 13, 19, 24, 29, 35, 40, 45, 51]$ (indices $1$ to $11$): it starts from $left=1$, $right=11$ and, while $left\le right$, examines $mid=left+\lfloor(right-left)/2\rfloor$, returns $mid$ if $a[mid]=m$, otherwise sets $left\leftarrow mid+1$ if $a[mid]<m$ and $right\leftarrow mid-1$ if $a[mid]>m$; at the end it returns $-1$. Which indices $mid$ does it examine, and what does it return?
$mid$: $6,\ 9,\ 10,\ 11$; returns $11$
$mid$: $6,\ 9,\ 11$; returns $11$
$mid$: $6,\ 3,\ 1$; returns $-1$
$mid$: $6,\ 9,\ 10$; returns $-1$
Explanation. With $mid=left+\lfloor(right-left)/2\rfloor$, if $a[mid]<m$ we set $left\leftarrow mid+1$, otherwise $right\leftarrow mid-1$: indices $6,\ 9,\ 10,\ 11$, returned value $11$.
Example 1 · alg-g-search-compare · level media · notes
We look for $m=51$ in the sorted array $a=[1, 14, 22, 28, 29, 39, 40, 42, 43, 49, 51, 56]$ (indices from $1$ to $12$). LinearSearch compares $a[i]=m$ for $i=1,2,\dots$ until the first success. BinarySearch starts from $left=1$, $right=12$ and at each iteration examines $mid=left+\lfloor(right-left)/2\rfloor$: it stops if $a[mid]=m$, otherwise it sets $left\leftarrow mid+1$ if $a[mid]<m$ and $right\leftarrow mid-1$ if $a[mid]>m$. How many comparisons does LinearSearch perform and how many iterations BinarySearch?
Explanation. $m$ is in position $11$, so LinearSearch performs $11$ comparisons. BinarySearch examines $mid=6,\ 9,\ 11$: $3$ iterations, no more than $\lfloor\log_2 12\rfloor+1=4$.
Example 2 · alg-g-search-compare · level media · notes
We look for $m=52$ in the sorted array $a=[13, 14, 15, 20, 28, 33, 37, 46, 52, 56, 57]$ (indices from $1$ to $11$). LinearSearch compares $a[i]=m$ for $i=1,2,\dots$ until the first success. BinarySearch starts from $left=1$, $right=11$ and at each iteration examines $mid=left+\lfloor(right-left)/2\rfloor$: it stops if $a[mid]=m$, otherwise it sets $left\leftarrow mid+1$ if $a[mid]<m$ and $right\leftarrow mid-1$ if $a[mid]>m$. How many comparisons does LinearSearch perform and how many iterations BinarySearch?
Explanation. $m$ is in position $9$, so LinearSearch performs $9$ comparisons. BinarySearch examines $mid=6,\ 9$: $2$ iterations, no more than $\lfloor\log_2 11\rfloor+1=4$.
5. Numerical algorithms (4)
Example 1 · alg-g-change-base · level facile · notes
ChangeOfBase$(n,b)$ repeatedly divides $n$ by the base $b$ until the quotient is $0$, and each remainder is the next digit starting from the least significant one. Which is the representation in base $8$ of $n=318$ (digits from the most to the least significant)?
$(674)_{8}$
$(476)_{8}$
$(47)_{8}$
$(506)_{8}$
Explanation. The remainders of the successive divisions by $8$ are $6,\ 7,\ 4$: they are the digits $d_0,d_1,\dots$, i.e., from the least significant one. Read in reverse order they give $(476)_{8}$.
Example 2 · alg-g-change-base · level facile · notes
ChangeOfBase$(n,b)$ repeatedly divides $n$ by the base $b$ until the quotient is $0$, and each remainder is the next digit starting from the least significant one. Which is the representation in base $8$ of $n=432$ (digits from the most to the least significant)?
$(670)_{8}$
$(66)_{8}$
$(660)_{8}$
$(066)_{8}$
Explanation. The remainders of the successive divisions by $8$ are $0,\ 6,\ 6$: they are the digits $d_0,d_1,\dots$, i.e., from the least significant one. Read in reverse order they give $(660)_{8}$.
EuclideanAlgorithm$(n,m)$ computes $\gcd(n,m)$: while $m\ne 0$, it replaces $(n,m)$ with $(m,\ n\bmod m)$ (one iteration of the while loop); then it returns $n$. With $n=128$ and $m=168$, which value does it return and after how many iterations?
returns $8$ after $3$ iterations
returns $8$ after $5$ iterations
returns $8$ after $4$ iterations
returns $40$ after $4$ iterations
Explanation. The values of $m$ are $168,\ 128,\ 40,\ 8,\ 0$: each iteration replaces $(n,m)$ with $(m,\ n\bmod m)$; after $4$ iterations $m=0$ and the algorithm returns $n=8=\gcd(128,168)$. With $n<m$ the first iteration just swaps the two numbers.
EuclideanAlgorithm$(n,m)$ computes $\gcd(n,m)$: while $m\ne 0$, it replaces $(n,m)$ with $(m,\ n\bmod m)$ (one iteration of the while loop); then it returns $n$. With $n=36$ and $m=66$, which value does it return and after how many iterations?
returns $6$ after $4$ iterations
returns $6$ after $3$ iterations
returns $6$ after $5$ iterations
returns $30$ after $4$ iterations
Explanation. The values of $m$ are $66,\ 36,\ 30,\ 6,\ 0$: each iteration replaces $(n,m)$ with $(m,\ n\bmod m)$; after $4$ iterations $m=0$ and the algorithm returns $n=6=\gcd(36,66)$. With $n<m$ the first iteration just swaps the two numbers.
SieveOfEratosthenes$(n)$ sets $prime[2..n]$ to $1$; then for $p=2,\dots,\lfloor\sqrt n\rfloor$, if $prime[p]=1$, it executes $prime[j]\leftarrow 0$ for $j=p^2,\,p^2+p,\,p^2+2p,\dots\le n$. With $n=47$, how many times is the assignment $prime[j]\leftarrow 0$ executed?
$40$
$31$
$50$
$44$
Explanation. The outer loop goes up to $\lfloor\sqrt{47}\rfloor=6$ and the inner loop runs only for $p$ prime ($p=2,3,5$), with $j=p^2,p^2+p,\dots\le 47$: $40$ assignments in total. A composite that is a multiple of several primes is marked several times, so the count is not the number of composites ($31$).
SieveOfEratosthenes$(n)$ sets $prime[2..n]$ to $1$; then for $p=2,\dots,\lfloor\sqrt n\rfloor$, if $prime[p]=1$, it executes $prime[j]\leftarrow 0$ for $j=p^2,\,p^2+p,\,p^2+2p,\dots\le n$. With $n=41$, how many times is the assignment $prime[j]\leftarrow 0$ executed?
$27$
$38$
$34$
$42$
Explanation. The outer loop goes up to $\lfloor\sqrt{41}\rfloor=6$ and the inner loop runs only for $p$ prime ($p=2,3,5$), with $j=p^2,p^2+p,\dots\le 41$: $34$ assignments in total. A composite that is a multiple of several primes is marked several times, so the count is not the number of composites ($27$).
A natural $d \ge 1$ is a divisor of $n$ if $n \bmod d=0$ ($1$ and $n$ included). How many divisors does $n=74$ have?
$4$
$2$
$5$
$3$
Explanation. The divisors are $1,2,37,74$: $4$ in total. Forgetting $1$ and $n$ removes two divisors; counting only those up to $\sqrt{n}$ forgets their companions $n/d$.
A natural $d \ge 1$ is a divisor of $n$ if $n \bmod d=0$ ($1$ and $n$ included). How many divisors does $n=45$ have?
$7$
$5$
$4$
$6$
Explanation. The divisors are $1,3,5,9,15,45$: $6$ in total. Forgetting $1$ and $n$ removes two divisors; counting only those up to $\sqrt{n}$ forgets their companions $n/d$.
6. Introduction to C++ (2)
Example 1 · alg-g-cpp-bitwise · level facile · notes
In C++, with <code>int x = 20, y = 26;</code>, what is the value of the expression <code>x ^ y</code>?
$30$
$16$
$14$
$46$
Explanation. $20=(10100)_2$ and $26=(11010)_2$; with <code>^</code> a bit is $1$ if it is $1$ in exactly one of them: $(01110)_2=14$.
Example 2 · alg-g-cpp-bitwise · level facile · notes
In C++, with <code>int x = 27, y = 13;</code>, what is the value of the expression <code>x | y</code>?
$40$
$22$
$9$
$31$
Explanation. $27=(11011)_2$ and $13=(01101)_2$; with <code>|</code> a bit is $1$ if it is $1$ in at least one of them: $(11111)_2=31$.
Example 1 · alg-g-cpp-reference · level media · notes
In C++ a parameter declared with <code>&</code> (for instance <code>int& b</code>) is passed by reference, the others by value. What does the program print?
<pre>int f(int& a, int b)
{
a = a + 4;
b = b * 4;
return a + b;
}
int main()
{
int x = 6, y = 6;
int z = f(x, y);
cout << x << " " << y << " " << z;
return 0;
}</pre>
<code>6 6 34</code>
<code>10 24 34</code>
<code>10 6 30</code>
<code>10 6 34</code>
Explanation. Inside <code>f</code> we have <code>a</code> $=6+4=10$ and <code>b</code> $=6\cdot 4=24$, so <code>z</code> $=34$. Only the parameter passed by reference (<code>a</code>) modifies the variable of the caller: <code>x</code> $=10$, <code>y</code> $=6$.
Example 2 · alg-g-cpp-reference · level media · notes
In C++ a parameter declared with <code>&</code> (for instance <code>int& b</code>) is passed by reference, the others by value. What does the program print?
<pre>int f(int& a, int b)
{
a = a + 2;
b = b * 2;
return a + b;
}
int main()
{
int x = 5, y = 8;
int z = f(x, y);
cout << x << " " << y << " " << z;
return 0;
}</pre>
<code>7 8 23</code>
<code>5 16 23</code>
<code>5 8 23</code>
<code>7 16 23</code>
Explanation. Inside <code>f</code> we have <code>a</code> $=5+2=7$ and <code>b</code> $=8\cdot 2=16$, so <code>z</code> $=23$. Only the parameter passed by reference (<code>a</code>) modifies the variable of the caller: <code>x</code> $=7$, <code>y</code> $=8$.
7. Introduction to Python (2)
Example 1 · alg-g-py-divmod · level facile · notes
In Python 3, what are <code>26 // -6</code> and <code>26 % -6</code> (in this order)?
$-5$ and $2$
$-4$ and $2$
$-5$ and $-4$
$-4$ and $-4$
Explanation. In Python <code>//</code> rounds the quotient down: $\lfloor 26/(-6)\rfloor=-5$; the remainder is $26-(-6)\cdot(-5)=-4$ and has the sign of the divisor. C++ and Java truncate toward zero and would give $-4$ and $2$.
Example 2 · alg-g-py-divmod · level facile · notes
In Python 3, what are <code>-19 // 8</code> and <code>-19 % 8</code> (in this order)?
$-2$ and $5$
$-3$ and $-3$
$-2$ and $-3$
$-3$ and $5$
Explanation. In Python <code>//</code> rounds the quotient down: $\lfloor -19/8\rfloor=-3$; the remainder is $-19-8\cdot(-3)=5$ and has the sign of the divisor. C++ and Java truncate toward zero and would give $-2$ and $-3$.
In Python a parameter receives the same object passed by the caller. What does the program print?
<pre>def f(a, x):
a[2] = a[2] + x
x = x * 2
return x
b = [6, 6, 8]
k = 2
r = f(b, k)
print(b, k, r)</pre>
<code>[6, 6, 8] 2 4</code>
<code>[6, 6, 10] 4 4</code>
<code>[6, 6, 12] 2 4</code>
<code>[6, 6, 10] 2 4</code>
Explanation. <code>a[2] = …</code> modifies an element of the caller's list, which becomes <code>[6, 6, 10]</code>; <code>x = x * 2</code> changes only the local name, so <code>k</code> stays $2$, while the returned value is $4$.
In Python a parameter receives the same object passed by the caller. What does the program print?
<pre>def f(a, x):
a[0] = a[0] + x
x = x * 2
return x
b = [4, 8, 3]
k = 4
r = f(b, k)
print(b, k, r)</pre>
<code>[8, 8, 3] 4 8</code>
<code>[8, 8, 3] 4 4</code>
<code>[4, 8, 3] 4 8</code>
<code>[8, 8, 3] 8 8</code>
Explanation. <code>a[0] = …</code> modifies an element of the caller's list, which becomes <code>[8, 8, 3]</code>; <code>x = x * 2</code> changes only the local name, so <code>k</code> stays $4$, while the returned value is $8$.
8. Introduction to Java (2)
Example 1 · alg-g-java-divmod · level facile · notes
In Java, with <code>int x = 26, y = -6;</code>, what does <code>System.out.println(x / y + " " + x % y);</code> print?
<code>-4 -4</code>
<code>-5 -4</code>
<code>-4 2</code>
<code>-5 2</code>
Explanation. Between two <code>int</code> values, <code>/</code> truncates the quotient toward zero: $-4$; the remainder is $26-(-6)\cdot(-4)=2$ and has the sign of the dividend. $-5$ and $-4$ are the results of <code>//</code> and <code>%</code> in Python, which rounds down.
Example 2 · alg-g-java-divmod · level facile · notes
In Java, with <code>int x = -19, y = 8;</code>, what does <code>System.out.println(x / y + " " + x % y);</code> print?
<code>-3 -3</code>
<code>-2 5</code>
<code>-3 5</code>
<code>-2 -3</code>
Explanation. Between two <code>int</code> values, <code>/</code> truncates the quotient toward zero: $-2$; the remainder is $-19-8\cdot(-2)=-3$ and has the sign of the dividend. $-3$ and $5$ are the results of <code>//</code> and <code>%</code> in Python, which rounds down.
Example 1 · alg-g-java-concat · level media · notes
In Java, with <code>int x = 8, y = 2;</code>, what does <code>System.out.println(x + " " + y * 2 + x);</code> print?
<code>8 12</code>
<code>8 20</code>
<code>8 228</code>
<code>8 48</code>
Explanation. The operator <code>+</code> is evaluated from left to right: between two <code>int</code> values it is an addition, but as soon as one of the two operands is a <code>String</code> the other is converted into text and concatenated. <code>*</code> and the parentheses are evaluated first. The result is <code>8 48</code>.
Example 2 · alg-g-java-concat · level media · notes
In Java, with <code>int x = 5, y = 8;</code>, what does <code>System.out.println(x + y + " " + x + y);</code> print?
<code>13 58</code>
<code>58 13</code>
<code>1358</code>
<code>58 58</code>
Explanation. The operator <code>+</code> is evaluated from left to right: between two <code>int</code> values it is an addition, but as soon as one of the two operands is a <code>String</code> the other is converted into text and concatenated. <code>*</code> and the parentheses are evaluated first. The result is <code>13 58</code>.
9. Asymptotic notation (3)
Example 1 · alg-g-asym-compare · level facile · notes
Let $f(n)=(n+4)^2$ and $g(n)=n^2\,2^n$, functions of the natural variable $n$. Which asymptotic relation is true?
$f(n)=\Theta\big(g(n)\big)$
$f(n)=\Omega\big(g(n)\big)$
$f(n)=o\big(g(n)\big)$
$f(n)=\omega\big(g(n)\big)$
Explanation. We have $\lim_{n\to+\infty} f(n)/g(n)=0^+$; by the limit criterion $f=o(g)$, hence also $f=\bigO(g)$, $g=\omega(f)$ and $g=\Omega(f)$, but neither $\Theta$ nor $\Omega$ of $f$ with respect to $g$.
Example 2 · alg-g-asym-compare · level facile · notes
Let $f(n)=\ln(n^3)$ and $g(n)=n\log_2 n$, functions of the natural variable $n$. Which asymptotic relation is true?
$f(n)=o\big(g(n)\big)$
$f(n)=\Theta\big(g(n)\big)$
$f(n)=\Omega\big(g(n)\big)$
$g(n)=\bigO\big(f(n)\big)$
Explanation. We have $\lim_{n\to+\infty} f(n)/g(n)=0^+$; by the limit criterion $f=o(g)$, hence also $f=\bigO(g)$, $g=\omega(f)$ and $g=\Omega(f)$, but neither $\Theta$ nor $\Omega$ of $f$ with respect to $g$.
Example 1 · alg-g-theta-constants · level media · notes
To prove with the definition that $f(n)=4n^2+7n=\Theta(n^2)$ we need constants $c_1,c_2>0$ and a threshold $n_1\in\N$ with $c_1n^2\le f(n)\le c_2n^2$ for all $n\ge n_1$. Which choice works?
$c_1=5$, $c_2=6$, $n_1=1$
$c_1=5$, $c_2=15$, $n_1=7$
$c_1=4$, $c_2=6$, $n_1=4$
$c_1=4$, $c_2=4$, $n_1=7$
Explanation. The lower bound $c_1n^2\le f(n)$ holds for all $n$ if and only if $c_1\le 4$. The upper one is equivalent to $7n\le(c_2-4)n^2$, i.e., $(c_2-4)\,n\ge 7$: we need $c_2>4$ and $n_1\ge 7/(c_2-4)$. With $c_2=6$ we have $2\cdot 4\ge 7$; the other choices violate one of the conditions.
Example 2 · alg-g-theta-constants · level media · notes
To prove with the definition that $f(n)=3n^2+8n=\Theta(n^2)$ we need constants $c_1,c_2>0$ and a threshold $n_1\in\N$ with $c_1n^2\le f(n)\le c_2n^2$ for all $n\ge n_1$. Which choice works?
$c_1=3$, $c_2=4$, $n_1=8$
$c_1=1$, $c_2=10$, $n_1=1$
$c_1=4$, $c_2=14$, $n_1=8$
$c_1=4$, $c_2=5$, $n_1=1$
Explanation. The lower bound $c_1n^2\le f(n)$ holds for all $n$ if and only if $c_1\le 3$. The upper one is equivalent to $8n\le(c_2-3)n^2$, i.e., $(c_2-3)\,n\ge 8$: we need $c_2>3$ and $n_1\ge 8/(c_2-3)$. With $c_2=4$ we have $1\cdot 8\ge 8$; the other choices violate one of the conditions.
Example 1 · alg-g-bigo-n1 · level complessa · notes
To prove $f(n)=4n^2+25n=O(n^2)$ the constant $c=7$ is chosen. What is the smallest natural $n_1$ such that $f(n) \le 7\,n^2$ for every $n \ge n_1$?
$10$
$8$
$9$
$4$
Explanation. For $n \ge 1$: $4n^2+25n \le 7n^2 \iff 25 \le 3n \iff n \ge 25/3$, so $n_1=\lceil 25/3\rceil=9$. With $n_1-1$ the inequality does not hold yet.
Example 2 · alg-g-bigo-n1 · level complessa · notes
To prove $f(n)=3n^2+35n=O(n^2)$ the constant $c=4$ is chosen. What is the smallest natural $n_1$ such that $f(n) \le 4\,n^2$ for every $n \ge n_1$?
$9$
$36$
$34$
$35$
Explanation. For $n \ge 1$: $3n^2+35n \le 4n^2 \iff 35 \le 1n \iff n \ge 35/1$, so $n_1=\lceil 35/1\rceil=35$. With $n_1-1$ the inequality does not hold yet.
10. Asymptotic growth (2)
Example 1 · alg-g-growth-order · level facile · notes
Sort by order of growth, from the slowest to the fastest (each one is $o$ of the next), the functions $2^n,\ 3n+\log_2 n,\ n\log_2 n,\ \sqrt{n}$.
Explanation. Hierarchy: polylogarithms $\prec$ powers $\prec$ exponentials $\prec$ $n!$ $\prec$ $n^n$; among powers the exponent matters, among exponentials the base, and constant factors or shifts do not change the order.
Example 2 · alg-g-growth-order · level facile · notes
Sort by order of growth, from the slowest to the fastest (each one is $o$ of the next), the functions $2^{2n},\ \log_2^3 n,\ n!,\ \log_2 n$.
$\log_2 n,\quad 2^{2n},\quad \log_2^3 n,\quad n!$
$\log_2^3 n,\quad \log_2 n,\quad 2^{2n},\quad n!$
$\log_2 n,\quad \log_2^3 n,\quad n!,\quad 2^{2n}$
$\log_2 n,\quad \log_2^3 n,\quad 2^{2n},\quad n!$
Explanation. Hierarchy: polylogarithms $\prec$ powers $\prec$ exponentials $\prec$ $n!$ $\prec$ $n^n$; among powers the exponent matters, among exponentials the base, and constant factors or shifts do not change the order.
Example 1 · alg-g-growth-transform · level media · notes
Let $f(n)=2^{n}$ and $g(n)=5^{n}$, functions of the natural variable $n$. Which asymptotic relation is true?
$f(n)=o\big(g(n)\big)$
Neither is $\bigO$ of the other
$f(n)=\omega\big(g(n)\big)$
$f(n)=\Theta\big(g(n)\big)$
Explanation. It holds $f(n)=o\big(g(n)\big)$: among exponentials the base matters. The notations $\Theta$, $o$ and $\omega$ are mutually exclusive.
Example 2 · alg-g-growth-transform · level media · notes
Let $f(n)=\log_2(n^{5})$ and $g(n)=\log_2 n$, functions of the natural variable $n$. Which asymptotic relation is true?
$f(n)=\Theta\big(g(n)\big)$
Neither is $\bigO$ of the other
$f(n)=\omega\big(g(n)\big)$
$f(n)=o\big(g(n)\big)$
Explanation. It holds $f(n)=\Theta\big(g(n)\big)$: $\log_2(n^k)=k\log_2 n$. The notations $\Theta$, $o$ and $\omega$ are mutually exclusive.
11. Input size (2)
Example 1 · alg-g-input-size · level facile · notes
The input is the array $a=[116, 158, 172, 22, 162]$ (without the number $n$). What is the input size $|I|$, i.e., the total number of bits needed to write it in binary?
$36$
$41$
$40$
$31$
Explanation. Each entry requires $\lfloor\log_2 a[i]\rfloor+1$ bits: $7+8+8+5+8=36$. The value $n(\lfloor\log_2 M\rfloor+1)=40$ is only an upper bound.
Example 2 · alg-g-input-size · level facile · notes
The input is the array $a=[169, 63, 19, 80, 172]$ (without the number $n$). What is the input size $|I|$, i.e., the total number of bits needed to write it in binary?
$34$
$29$
$40$
$39$
Explanation. Each entry requires $\lfloor\log_2 a[i]\rfloor+1$ bits: $8+6+5+7+8=34$. The value $n(\lfloor\log_2 M\rfloor+1)=40$ is only an upper bound.
Example 1 · alg-g-input-zeros · level media · notes
The input size $|I|$ is the total number of bits needed to write the instance in binary: a natural number $x\ge 1$ needs $\lfloor\log_2 x\rfloor+1$ bits, and zero one bit. The input is the array $a=[158, 22, 125, 177, 0, 37]$ together with the number $n=6$ of its entries. What is $|I|$?
$35$
$39$
$51$
$38$
Explanation. The entries need $8+5+7+8+1+6=35$ bits (each zero counts one bit) and $n=6$ needs $3$ more: $|I|=38$.
Example 2 · alg-g-input-zeros · level media · notes
The input size $|I|$ is the total number of bits needed to write the instance in binary: a natural number $x\ge 1$ needs $\lfloor\log_2 x\rfloor+1$ bits, and zero one bit. The input is the array $a=[63, 0, 172, 132, 151, 174]$ (without the number $n$). What is $|I|$?
$48$
$45$
$39$
$42$
Explanation. The entries need $6+1+8+8+8+8=39$ bits (each zero counts one bit): $|I|=39$.
12. Running time (3)
Example 1 · alg-g-loop-count · level facile · notes
How many times is line $4$ executed?
<pre>1 x := 0
2 i := 1
3 <b>while</b> i ≤ 14 <b>do</b>
4 x ← x + 1
5 i ← 2 · i
<b>end</b></pre>
$3$
$4$
$5$
$7$
Explanation. Count line by line: $i=1,2,4,\dots,2^{3}\le 14\text{: }\lfloor\log_2 14\rfloor+1=4$.
Example 2 · alg-g-loop-count · level facile · notes
How many times is line $4$ executed?
<pre>1 x := 0
2 <b>for</b> i := 1 <b>to</b> 18 <b>do</b>
3 <b>for</b> j := 1 <b>to</b> i − 1 <b>do</b>
4 x ← x + 1
<b>end</b>
<b>end</b></pre>
$289$
$324$
$153$
$171$
Explanation. Count line by line: $\sum_{i=1}^{18}(i-1)=\frac{18\cdot 17}{2}=153$.
Example 1 · alg-g-findmax-steps · level media · notes
FindMaximum (pseudo-code below) is executed on $a=[18, 24, 26, 4, 25, 19, 19, 27]$, with $n=8$. Counting one step for each execution of a numbered line (return included), how many steps does it execute?
<pre>1 max := a[1]
2 i := 2
3 <b>while</b> i ≤ n <b>do</b>
4 <b>if</b> a[i] > max <b>then</b>
5 max ← a[i]
<b>end</b>
6 i ← i + 1
<b>end</b>
7 <b>return</b> max</pre>
$32$
$29$
$27$
$28$
Explanation. Lines $1,2,7$: once each; condition of line $3$: $n=8$ times; lines $4$ and $6$: $n-1=7$ times; line $5$: $t=3$ times (new maxima). Total $3n+t+1=28$; $4n$ is the worst case $t=n-1$.
Example 2 · alg-g-findmax-steps · level media · notes
FindMaximum (pseudo-code below) is executed on $a=[26, 10, 3, 12, 26, 24, 20]$, with $n=7$. Counting one step for each execution of a numbered line (return included), how many steps does it execute?
<pre>1 max := a[1]
2 i := 2
3 <b>while</b> i ≤ n <b>do</b>
4 <b>if</b> a[i] > max <b>then</b>
5 max ← a[i]
<b>end</b>
6 i ← i + 1
<b>end</b>
7 <b>return</b> max</pre>
$22$
$28$
$21$
$23$
Explanation. Lines $1,2,7$: once each; condition of line $3$: $n=7$ times; lines $4$ and $6$: $n-1=6$ times; line $5$: $t=0$ times (new maxima). Total $3n+t+1=22$; $4n$ is the worst case $t=n-1$.
Example 1 · alg-g-nested-loops · level complessa · notes
With $n=7$, how many times is the statement $x:=x+1$ executed in the fragment «for $i=1$ to $n$: for $j=i$ to $n$: for $k=1$ to $j$: $x:=x+1$» (every for includes both bounds; if the initial bound exceeds the final one the loop is not executed)?
$28$
$140$
$49$
$343$
Explanation. Sum over the pairs $i \le j$: $\sum_{i=1}^{n}\sum_{j=i}^{n} j=140$. Counting $n$ iterations for every loop ignores that the inner loops depend on $i$ and $j$.
Example 2 · alg-g-nested-loops · level complessa · notes
With $n=6$, how many times is the statement $x:=x+1$ executed in the fragment «for $i=1$ to $n$: for $j=i$ to $n$: for $k=i$ to $j$: $x:=x+1$» (every for includes both bounds; if the initial bound exceeds the final one the loop is not executed)?
$216$
$36$
$56$
$21$
Explanation. Sum over the pairs $i \le j$: $\sum_{i=1}^{n}\sum_{j=i}^{n}(j-i+1)=56$. Counting $n$ iterations for every loop ignores that the inner loops depend on $i$ and $j$.
13. Correctness (2)
Example 1 · alg-g-findmax-invariant · level facile · notes
FindMaximum (below) is executed on $a=[25, 7, 14, 18, 34, 31, 24]$, with $n=7$. What are the values of $i$ and $max$ when the condition of line $3$ is evaluated for the $3$-th time?
<pre>1 max := a[1]
2 i := 2
3 <b>while</b> i ≤ n <b>do</b>
4 <b>if</b> a[i] > max <b>then</b>
5 max ← a[i]
<b>end</b>
6 i ← i + 1
<b>end</b>
7 <b>return</b> max</pre>
$i=4$, $max=18$
$i=4$, $max=14$
$i=3$, $max=25$
$i=4$, $max=25$
Explanation. At the first evaluation $i=2$ and $max=a[1]$; each iteration increments $i$. At evaluation number $3$ we have $i=4$ and, by the invariant $max=\max\{a[1],\dots,a[i-1]\}$, $max=\max\{a[1],\dots,a[3]\}=25$.
Example 2 · alg-g-findmax-invariant · level facile · notes
FindMaximum (below) is executed on $a=[38, 13, 18, 25, 8, 36, 32]$, with $n=7$. What are the values of $i$ and $max$ when the condition of line $3$ is evaluated for the $5$-th time?
<pre>1 max := a[1]
2 i := 2
3 <b>while</b> i ≤ n <b>do</b>
4 <b>if</b> a[i] > max <b>then</b>
5 max ← a[i]
<b>end</b>
6 i ← i + 1
<b>end</b>
7 <b>return</b> max</pre>
$i=5$, $max=38$
$i=6$, $max=36$
$i=6$, $max=8$
$i=6$, $max=38$
Explanation. At the first evaluation $i=2$ and $max=a[1]$; each iteration increments $i$. At evaluation number $5$ we have $i=6$ and, by the invariant $max=\max\{a[1],\dots,a[i-1]\}$, $max=\max\{a[1],\dots,a[5]\}=38$.
Example 1 · alg-g-binsearch-interval · level media · notes
BinarySearch (below) looks for $m=6$ in $a=[6, 7, 8, 17, 24, 29, 40, 41, 44, 50, 56, 60, 62, 70]$, with $n=14$. What are $left$ and $right$ when the condition of line $3$ is evaluated for the $3$-th time?
<pre>1 left := 1
2 right := n
3 <b>while</b> left ≤ right <b>do</b>
4 mid := left + ⌊(right − left) / 2⌋
5 <b>if</b> a[mid] = m <b>then return</b> mid
6 <b>if</b> a[mid] < m <b>then</b> left ← mid + 1
7 <b>else</b> right ← mid − 1
<b>end</b>
8 <b>return</b> −1</pre>
$left=0$, $right=2$
$left=1$, $right=3$
$left=1$, $right=2$
$left=1$, $right=6$
Explanation. At the successive evaluations the interval is $[1,14]$, $[1,6]$, $[1,2]$. Each step discards only a part that cannot contain $m$ (invariant: if $m$ is in the array, it is in $a[left..right]$).
Example 2 · alg-g-binsearch-interval · level media · notes
BinarySearch (below) looks for $m=6$ in $a=[4, 13, 16, 31, 33, 42, 46, 55, 61, 63, 69]$, with $n=11$. What are $left$ and $right$ when the condition of line $3$ is evaluated for the $2$-th time?
<pre>1 left := 1
2 right := n
3 <b>while</b> left ≤ right <b>do</b>
4 mid := left + ⌊(right − left) / 2⌋
5 <b>if</b> a[mid] = m <b>then return</b> mid
6 <b>if</b> a[mid] < m <b>then</b> left ← mid + 1
7 <b>else</b> right ← mid − 1
<b>end</b>
8 <b>return</b> −1</pre>
$left=1$, $right=6$
$left=1$, $right=5$
$left=0$, $right=5$
$left=1$, $right=2$
Explanation. At the successive evaluations the interval is $[1,11]$, $[1,5]$. Each step discards only a part that cannot contain $m$ (invariant: if $m$ is in the array, it is in $a[left..right]$).
14. Recursion (5)
Example 1 · alg-g-rec-calls · level facile · notes
FastPower$(x,n)$ computes $x^n$: if $n=0$ it returns $1$; otherwise it sets $y:=$FastPower$(x,\lfloor n/2\rfloor)$ and returns $y\cdot y$ ($n$ even) or $x\cdot y\cdot y$ ($n$ odd). How many calls (including the first one) does FastPower$(x,60)$ execute?
$6$
$7$
$8$
$61$
Explanation. The exponents are $60,\lfloor 60/2\rfloor,\dots,1,0$: as many calls as the binary digits of $60$ plus the one with exponent $0$, i.e., $\lfloor\log_2 60\rfloor+2=7$.
Example 2 · alg-g-rec-calls · level facile · notes
Hanoi$(n,from,to,aux)$ moves a tower of $n$ disks: if $n=1$ it moves the disk; otherwise it moves $n-1$ disks to $aux$ with one call, moves disk $n$ to $to$ and brings the $n-1$ disks onto $to$ with another call. How many moves does it execute with $n=9$?
$81$
$255$
$511$
$512$
Explanation. $M(n)=2M(n-1)+1$ with $M(1)=1$, hence $M(n)=2^n-1=511$.
Example 1 · alg-g-rec-value · level facile · notes
What does the call R$(4)$ return, and how many calls of R does it execute in total (including the first one)?
<pre><b>function</b> R(n)
<b>if</b> n = 0 <b>then</b> <b>return</b> 2
<b>if</b> n = 1 <b>then</b> <b>return</b> 3
<b>return</b> 2 · R(n − 1) + 2 · R(n − 2)
<b>end</b></pre>
value $72$, $9$ calls
value $26$, $9$ calls
value $72$, $5$ calls
value $72$, $10$ calls
Explanation. The values $R(0),\dots,R(4)$ are $2,\ 3,\ 10,\ 26,\ 72$. The tree of recursive calls is that of Fib: $C(n)=C(n-1)+C(n-2)+1$, $C(0)=C(1)=1$, hence $9$ calls (not $n+1$: the subproblems are repeated).
Example 2 · alg-g-rec-value · level facile · notes
What does the call R$(5)$ return, and how many calls of R does it execute in total (including the first one)?
<pre><b>function</b> R(n)
<b>if</b> n = 0 <b>then</b> <b>return</b> 0
<b>if</b> n = 1 <b>then</b> <b>return</b> 1
<b>return</b> 2 · R(n − 1) + 3 · R(n − 2)
<b>end</b></pre>
value $61$, $15$ calls
value $61$, $6$ calls
value $20$, $15$ calls
value $61$, $16$ calls
Explanation. The values $R(0),\dots,R(5)$ are $0,\ 1,\ 2,\ 7,\ 20,\ 61$. The tree of recursive calls is that of Fib: $C(n)=C(n-1)+C(n-2)+1$, $C(0)=C(1)=1$, hence $15$ calls (not $n+1$: the subproblems are repeated).
Example 1 · alg-g-fastpower-mults · level media · notes
How many calls of FastPower (including the first one) and how many multiplications in total does FastPower$(x,71)$ execute? ($y\cdot y$ counts one multiplication, $x\cdot y\cdot y$ two.)
<pre><b>function</b> FastPower(x, n)
<b>if</b> n = 0 <b>then</b> <b>return</b> 1
y := FastPower(x, ⌊n/2⌋)
<b>if</b> n mod 2 = 0 <b>then</b> <b>return</b> y · y
<b>else</b> <b>return</b> x · y · y
<b>end</b></pre>
$8$ calls, $11$ multiplications
$7$ calls, $11$ multiplications
$8$ calls, $70$ multiplications
$8$ calls, $14$ multiplications
Explanation. The exponents of the calls are $71,35,17,8,4,2,1,0$: $8$ calls. Each of the $7$ calls with positive exponent makes one multiplication, plus a second one if the exponent is odd ($4$ times, the $1$s in $(1000111)_2$): $7+4=11$, against the $70$ of the direct computation.
Example 2 · alg-g-fastpower-mults · level media · notes
How many calls of FastPower (including the first one) and how many multiplications in total does FastPower$(x,49)$ execute? ($y\cdot y$ counts one multiplication, $x\cdot y\cdot y$ two.)
<pre><b>function</b> FastPower(x, n)
<b>if</b> n = 0 <b>then</b> <b>return</b> 1
y := FastPower(x, ⌊n/2⌋)
<b>if</b> n mod 2 = 0 <b>then</b> <b>return</b> y · y
<b>else</b> <b>return</b> x · y · y
<b>end</b></pre>
$6$ calls, $9$ multiplications
$7$ calls, $12$ multiplications
$7$ calls, $9$ multiplications
$7$ calls, $48$ multiplications
Explanation. The exponents of the calls are $49,24,12,6,3,1,0$: $7$ calls. Each of the $6$ calls with positive exponent makes one multiplication, plus a second one if the exponent is odd ($3$ times, the $1$s in $(110001)_2$): $6+3=9$, against the $48$ of the direct computation.
Example 1 · alg-g-hanoi-moves · level facile · notes
Hanoi$(n,from,to,aux)$ with $n \ge 2$ recursively moves $n-1$ disks from $from$ to $aux$, then disk $n$ from $from$ to $to$ (one move), then $n-1$ disks from $aux$ to $to$; with $n=1$ it makes a single move. How many moves does it make with $n=9$ disks?
$511$
$512$
$17$
$255$
Explanation. $M(1)=1$ and $M(n)=2M(n-1)+1$, hence $M(n)=2^n-1=511$. $2^n$ forgets the $-1$.
Example 2 · alg-g-hanoi-moves · level facile · notes
Hanoi$(n,from,to,aux)$ with $n \ge 2$ recursively moves $n-1$ disks from $from$ to $aux$, then disk $n$ from $from$ to $to$ (one move), then $n-1$ disks from $aux$ to $to$; with $n=1$ it makes a single move. How many moves does it make with $n=7$ disks?
$128$
$63$
$127$
$13$
Explanation. $M(1)=1$ and $M(n)=2M(n-1)+1$, hence $M(n)=2^n-1=127$. $2^n$ forgets the $-1$.
Example 1 · alg-g-hanoi-move · level complessa · notes
Hanoi$(k,from,to,aux)$: if $k=0$ it does nothing; otherwise it runs Hanoi$(k-1,from,aux,to)$, moves disk $k$ from $from$ to $to$, and runs Hanoi$(k-1,aux,to,from)$. Hanoi$(4,1,3,2)$ is called (disks $1,\dots,4$ from the smallest, all on peg $1$). Which is move number $9$?
disk $1$ from peg $3$ to peg $2$
disk $1$ from peg $2$ to peg $3$
disk $4$ from peg $1$ to peg $3$
disk $2$ from peg $2$ to peg $1$
Explanation. The first moves are $1$: $1$ ($1\to2$), $2$: $2$ ($1\to3$), $3$: $1$ ($2\to3$), $4$: $3$ ($1\to2$), $5$: $1$ ($3\to1$), $6$: $2$ ($3\to2$), $7$: $1$ ($1\to2$), $8$: $4$ ($1\to3$), $9$: $1$ ($2\to3$), $10$: $2$ ($2\to1$). The call tree is followed in order: first the whole left subtree, then the move of the node, then the right subtree.
Example 2 · alg-g-hanoi-move · level complessa · notes
Hanoi$(k,from,to,aux)$: if $k=0$ it does nothing; otherwise it runs Hanoi$(k-1,from,aux,to)$, moves disk $k$ from $from$ to $to$, and runs Hanoi$(k-1,aux,to,from)$. Hanoi$(4,1,3,2)$ is called (disks $1,\dots,4$ from the smallest, all on peg $1$). Which is move number $12$?
disk $1$ from peg $1$ to peg $2$
disk $1$ from peg $3$ to peg $1$
disk $3$ from peg $2$ to peg $3$
disk $3$ from peg $3$ to peg $2$
Explanation. The first moves are $1$: $1$ ($1\to2$), $2$: $2$ ($1\to3$), $3$: $1$ ($2\to3$), $4$: $3$ ($1\to2$), $5$: $1$ ($3\to1$), $6$: $2$ ($3\to2$), $7$: $1$ ($1\to2$), $8$: $4$ ($1\to3$), $9$: $1$ ($2\to3$), $10$: $2$ ($2\to1$), $11$: $1$ ($3\to1$), $12$: $3$ ($2\to3$), $13$: $1$ ($1\to2$). The call tree is followed in order: first the whole left subtree, then the move of the node, then the right subtree.
15. Recurrences (2)
Example 1 · alg-g-rec-expansion · level media · notes
Let $T(1)=1$ and $T(n)=3T(n/2)+n$ for $n\ge 2$ a power of $2$. What is $T(32)$?
$908$
$422$
$665$
$503$
Explanation. Expanding, $T(n)=a^{k}T(1)+\sum_{j=0}^{k-1}a^j f(n/2^j)$ with $k=5$: $243+32+48+72+108+162=665$.
Example 2 · alg-g-rec-expansion · level media · notes
Let $T(1)=1$ and $T(n)=2T(n/2)+n^2$ for $n\ge 2$ a power of $2$. What is $T(8)$?
$104$
$128$
$112$
$120$
Explanation. Expanding, $T(n)=a^{k}T(1)+\sum_{j=0}^{k-1}a^j f(n/2^j)$ with $k=3$: $8+64+32+16=120$.
Example 1 · alg-g-rec-floor · level complessa · notes
Let $T(1)=1$ and $T(n)=T(\lfloor n/2\rfloor)+T(\lceil n/2\rceil)+n$ for $n\ge 2$ (the recurrence of MergeSort with unit constants). What is $T(17)$?
$87$
$85$
$81$
$102$
Explanation. We compute bottom-up the values that are needed: $T(2)=4,\ T(3)=8,\ T(4)=12,\ T(5)=17,\ T(8)=32,\ T(9)=38,\ T(17)=87$. The formula $n\log_2 n+n$ holds only for $n$ a power of $2$, and replacing $T(\lceil n/2\rceil)$ with $T(\lfloor n/2\rfloor)$ gives $81$.
Example 2 · alg-g-rec-floor · level complessa · notes
Let $T(1)=1$ and $T(n)=T(\lfloor n/2\rfloor)+T(\lceil n/2\rceil)+n$ for $n\ge 2$ (the recurrence of MergeSort with unit constants). What is $T(14)$?
$56$
$70$
$68$
$48$
Explanation. We compute bottom-up the values that are needed: $T(2)=4,\ T(3)=8,\ T(4)=12,\ T(7)=27,\ T(14)=68$. The formula $n\log_2 n+n$ holds only for $n$ a power of $2$, and replacing $T(\lceil n/2\rceil)$ with $T(\lfloor n/2\rfloor)$ gives $48$.
Using the Master Theorem, what is the order of growth of the solution of $T(n)=2\,T(n/4)+n$?
$T(n)=\Theta\big(\sqrt{n}\big)$
$T(n)=\Theta\big(n\big)$
$T(n)=\Theta\big(\sqrt{n}\,\log n\big)$
$T(n)=\Theta\big(n\,\log n\big)$
Explanation. Compare $f(n)=n$ with $n^{\log_b a}=n^{\log_{4} 2}=\sqrt{n}$: $f$ is polynomially larger and the regularity condition holds (case 3), hence $T(n)=\Theta(f(n))$.
Using the Master Theorem, what is the order of growth of the solution of $T(n)=3\,T(n/3)+n^{3}$?
$T(n)=\Theta\big(n^{3}\,\log n\big)$
$T(n)=\Theta\big(n\,\log n\big)$
$T(n)=\Theta\big(n^{3}\big)$
$T(n)=\Theta\big(n\big)$
Explanation. Compare $f(n)=n^{3}$ with $n^{\log_b a}=n^{\log_{3} 3}=n$: $f$ is polynomially larger and the regularity condition holds (case 3), hence $T(n)=\Theta(f(n))$.
Example 1 · alg-g-master-log · level complessa · notes
With the Master Theorem, what is the order of growth of the solution of $T(n)=9\,T(n/3)+n^{3}\,\log^{2} n$ (logarithms in base $2$)?
$T(n)=\Theta\big(n^{2}\,\log^{3} n\big)$
$T(n)=\Theta\big(n^{3}\,\log^{3} n\big)$
$T(n)=\Theta\big(n^{3}\big)$
$T(n)=\Theta\big(n^{3}\,\log^{2} n\big)$
Explanation. We compare $f(n)=n^{3}\,\log^{2} n$ with $n^{\log_b a}=n^{\log_{3} 9}=n^{2}$. $f$ is polynomially larger than $n^{2}$ and the regularity condition holds ($a\,f(n/b)\le\frac{9}{27}f(n)$), hence (case 3) $T(n)=\Theta(f(n))=\Theta(n^{3}\,\log^{2} n)$.
Example 2 · alg-g-master-log · level complessa · notes
With the Master Theorem, what is the order of growth of the solution of $T(n)=27\,T(n/3)+n^{2}$ (logarithms in base $2$)?
$T(n)=\Theta\big(n^{2}\,\log n\big)$
$T(n)=\Theta\big(n^{3}\big)$
$T(n)=\Theta\big(n^{3}\,\log n\big)$
$T(n)=\Theta\big(n^{4}\big)$
Explanation. We compare $f(n)=n^{2}$ with $n^{\log_b a}=n^{\log_{3} 27}=n^{3}$. $f$ is polynomially smaller than $n^{3}$ (case 1): $T(n)=\Theta(n^{3})$.
Merge$(a,l,m,r)$ copies the sorted halves into $L=a[l..m]$ and $R=a[m+1..r]$; while neither is exhausted it compares $L[i]\le R[j]$ and copies the smaller into $a$; then it copies the rest with no comparison. With $L=[5, 6, 7, 18]$ and $R=[4, 8, 9, 15]$, how many times does it execute the comparison $L[i]\le R[j]$?
$6$
$4$
$8$
$7$
Explanation. Each iteration of the first while loop makes one comparison and copies one element; the loop ends when one of the two halves is exhausted, and the rest of the other is copied without comparisons: $7$ comparisons ($n_1+n_2-1=7$ is only the maximum).
Merge$(a,l,m,r)$ copies the sorted halves into $L=a[l..m]$ and $R=a[m+1..r]$; while neither is exhausted it compares $L[i]\le R[j]$ and copies the smaller into $a$; then it copies the rest with no comparison. With $L=[3, 6, 9]$ and $R=[1, 4, 5, 20]$, how many times does it execute the comparison $L[i]\le R[j]$?
$7$
$5$
$3$
$6$
Explanation. Each iteration of the first while loop makes one comparison and copies one element; the loop ends when one of the two halves is exhausted, and the rest of the other is copied without comparisons: $6$ comparisons ($n_1+n_2-1=6$ is only the maximum).
Example 1 · alg-g-mergesort-total · level complessa · notes
MergeSort$(a,l,r)$, if $l<r$, recursively sorts $a[l..m]$ and $a[m+1..r]$ with $m=\lfloor(l+r)/2\rfloor$ and merges them with Merge, which compares $L[i]\le R[j]$ until one of the two halves is exhausted. For MergeSort$(a,1,8)$ on $a=[5, 4, 6, 8, 10, 7, 20, 3]$, how many comparisons $L[i]\le R[j]$ are executed in total?
$6$
$15$
$24$
$17$
Explanation. There are $4$ merges of pairs, $2$ of quadruples and a final one, each counting the comparisons until one half is exhausted: $15$ in total (the final merge makes $6$). $17$ is the maximum possible ($4\cdot1+2\cdot3+7$).
Example 2 · alg-g-mergesort-total · level complessa · notes
MergeSort$(a,l,r)$, if $l<r$, recursively sorts $a[l..m]$ and $a[m+1..r]$ with $m=\lfloor(l+r)/2\rfloor$ and merges them with Merge, which compares $L[i]\le R[j]$ until one of the two halves is exhausted. For MergeSort$(a,1,8)$ on $a=[17, 11, 4, 3, 5, 18, 1, 10]$, how many comparisons $L[i]\le R[j]$ are executed in total?
$7$
$16$
$17$
$24$
Explanation. There are $4$ merges of pairs, $2$ of quadruples and a final one, each counting the comparisons until one half is exhausted: $16$ in total (the final merge makes $7$). $17$ is the maximum possible ($4\cdot1+2\cdot3+7$).
Example 1 · alg-g-kadane · level complessa · notes
Kadane$(a,n)$ solves the maximum subarray problem: it returns the triple $(bl,br,best)$, where $a[bl..br]$ is a (non-empty, contiguous) subarray of maximum sum and $best$ is its sum (in the proposed instances the maximum-sum subarray is unique). What does Kadane$(a,8)$ return on $a=[9, -3, -3, -8, -5, 1, 4, 3]$?
$(bl,br,best)=(1,1,10)$
$(bl,br,best)=(1,8,-2)$
$(bl,br,best)=(1,1,9)$
$(bl,br,best)=(1,8,17)$
Explanation. Kadane scans the array keeping $cur$, the maximum sum of a subarray ending at the previous position: at position $i$ it restarts from $a[i]$ if $cur<0$, otherwise it extends with $a[i]$. The maximum is $a[1..1]$ with sum $9$. The sum of the positive entries only ($17$) does not correspond to a contiguous subarray.
Example 2 · alg-g-kadane · level complessa · notes
Kadane$(a,n)$ solves the maximum subarray problem: it returns the triple $(bl,br,best)$, where $a[bl..br]$ is a (non-empty, contiguous) subarray of maximum sum and $best$ is its sum (in the proposed instances the maximum-sum subarray is unique). What does Kadane$(a,8)$ return on $a=[-2, 6, -4, -8, -2, 7, 6, 3]$?
$(bl,br,best)=(6,8,16)$
$(bl,br,best)=(2,8,22)$
$(bl,br,best)=(2,8,8)$
$(bl,br,best)=(1,8,6)$
Explanation. Kadane scans the array keeping $cur$, the maximum sum of a subarray ending at the previous position: at position $i$ it restarts from $a[i]$ if $cur<0$, otherwise it extends with $a[i]$. The maximum is $a[6..8]$ with sum $16$. The sum of the positive entries only ($22$) does not correspond to a contiguous subarray.
Example 1 · alg-g-recsum-depth · level facile · notes
RecursiveSum$(a,l,r)$ returns $a[l]$ if $l=r$; otherwise, with $m=\lfloor (l+r)/2\rfloor$, it returns RecursiveSum$(a,l,m)+$RecursiveSum$(a,m+1,r)$. Called on an array of $n=116$ elements, what is the recursion depth, that is, the maximum number of calls active at the same time (the initial call included)?
$8$
$7$
$9$
$231$
Explanation. The call tree has height $\lceil \log_2 n\rceil=7$ (the larger half has $\lceil k/2\rceil$ elements), so the depth is $7+1=8$. $2n-1=231$ is the total number of calls.
Example 2 · alg-g-recsum-depth · level facile · notes
RecursiveSum$(a,l,r)$ returns $a[l]$ if $l=r$; otherwise, with $m=\lfloor (l+r)/2\rfloor$, it returns RecursiveSum$(a,l,m)+$RecursiveSum$(a,m+1,r)$. Called on an array of $n=79$ elements, what is the recursion depth, that is, the maximum number of calls active at the same time (the initial call included)?
$7$
$157$
$8$
$9$
Explanation. The call tree has height $\lceil \log_2 n\rceil=7$ (the larger half has $\lceil k/2\rceil$ elements), so the depth is $7+1=8$. $2n-1=157$ is the total number of calls.
FibRec$(k)$ returns $k$ if $k\le 1$, otherwise FibRec$(k-1)+$FibRec$(k-2)$. FibMemo$(k,memo)$ does the same, but if $memo[k]$ is already defined it returns it with no further call, and otherwise it stores the result in $memo[k]$. How many calls (including the first one) do FibRec$(8)$ and FibMemo$(8,memo)$ execute, with $memo$ all undefined?
FibRec: $67$, FibMemo: $15$
FibRec: $67$, FibMemo: $9$
FibRec: $67$, FibMemo: $17$
FibRec: $21$, FibMemo: $15$
Explanation. FibRec: $C(n)=2F(n+1)-1=67$ (overlapping subproblems). FibMemo: each value is computed once, $M(n)=M(n-1)+2$ with $M(2)=3$, hence $2n-1=15$.
FibRec$(k)$ returns $k$ if $k\le 1$, otherwise FibRec$(k-1)+$FibRec$(k-2)$. FibMemo$(k,memo)$ does the same, but if $memo[k]$ is already defined it returns it with no further call, and otherwise it stores the result in $memo[k]$. How many calls (including the first one) do FibRec$(7)$ and FibMemo$(7,memo)$ execute, with $memo$ all undefined?
FibRec: $41$, FibMemo: $8$
FibRec: $13$, FibMemo: $13$
FibRec: $41$, FibMemo: $13$
FibRec: $41$, FibMemo: $15$
Explanation. FibRec: $C(n)=2F(n+1)-1=41$ (overlapping subproblems). FibMemo: each value is computed once, $M(n)=M(n-1)+2$ with $M(2)=3$, hence $2n-1=13$.
Example 1 · alg-g-bottomup-pass · level complessa · notes
MergeSortBottomUp$(a,n)$ (below; Merge$(a,l,m,r)$ merges the sorted subarrays $a[l..m]$ and $a[m+1..r]$ into the sorted $a[l..r]$) is executed on $a=[3, 25, 30, 13, 26, 27, 10]$, with $n=7$. What does $a$ contain at the end of the pass with $width=2$?
<pre>width := 1
<b>while</b> width < n <b>do</b>
l := 1
<b>while</b> l + width ≤ n <b>do</b>
m := l + width − 1
r := min(l + 2·width − 1, n)
Merge(a, l, m, r)
l ← l + 2·width
<b>end</b>
width ← 2·width
<b>end</b></pre>
$[3, 13, 25, 30, 10, 26, 27]$
$[3, 13, 25, 30, 26, 27, 10]$
$[3, 10, 13, 25, 26, 27, 30]$
$[3, 25, 13, 30, 26, 27, 10]$
Explanation. The pass with $width=1$ merges the pairs $a[1..2]$, $a[3..4]$, $a[5..6]$ ($a[7]$ stays alone): $[3, 25, 13, 30, 26, 27, 10]$. The pass with $width=2$ merges $a[1..2]$ with $a[3..4]$ and $a[5..6]$ with $a[7..7]$ (incomplete block, with $r=\min(8,7)=7$): $[3, 13, 25, 30, 10, 26, 27]$.
Example 2 · alg-g-bottomup-pass · level complessa · notes
MergeSortBottomUp$(a,n)$ (below; Merge$(a,l,m,r)$ merges the sorted subarrays $a[l..m]$ and $a[m+1..r]$ into the sorted $a[l..r]$) is executed on $a=[13, 5, 4, 30, 28, 7, 26]$, with $n=7$. What does $a$ contain at the end of the pass with $width=2$?
<pre>width := 1
<b>while</b> width < n <b>do</b>
l := 1
<b>while</b> l + width ≤ n <b>do</b>
m := l + width − 1
r := min(l + 2·width − 1, n)
Merge(a, l, m, r)
l ← l + 2·width
<b>end</b>
width ← 2·width
<b>end</b></pre>
$[4, 5, 13, 30, 7, 26, 28]$
$[4, 5, 13, 30, 7, 28, 26]$
$[4, 5, 7, 13, 26, 28, 30]$
$[5, 13, 4, 30, 7, 28, 26]$
Explanation. The pass with $width=1$ merges the pairs $a[1..2]$, $a[3..4]$, $a[5..6]$ ($a[7]$ stays alone): $[5, 13, 4, 30, 7, 28, 26]$. The pass with $width=2$ merges $a[1..2]$ with $a[3..4]$ and $a[5..6]$ with $a[7..7]$ (incomplete block, with $r=\min(8,7)=7$): $[4, 5, 13, 30, 7, 26, 28]$.
Example 1 · alg-g-fib-calls · level facile · notes
FibRec$(n)$ returns $n$ if $n \le 1$, otherwise FibRec$(n-1)+$FibRec$(n-2)$. How many calls (the initial call included) does FibRec$(10)$ make?
$177$
$89$
$55$
$1023$
Explanation. The calls satisfy $C(0)=C(1)=1$ and $C(n)=1+C(n-1)+C(n-2)$, hence $C(n)=2F(n+1)-1=2 \cdot 89-1=177$: they grow as $\varphi^n$, not as $2^n$.
Example 2 · alg-g-fib-calls · level facile · notes
FibRec$(n)$ returns $n$ if $n \le 1$, otherwise FibRec$(n-1)+$FibRec$(n-2)$. How many calls (the initial call included) does FibRec$(8)$ make?
$34$
$255$
$67$
$21$
Explanation. The calls satisfy $C(0)=C(1)=1$ and $C(n)=1+C(n-1)+C(n-2)$, hence $C(n)=2F(n+1)-1=2 \cdot 34-1=67$: they grow as $\varphi^n$, not as $2^n$.