Mathematics for Computer Science 201-N11 • CEGEP, Montreal

Corrected practice final exam: Mathematics for Computer Science (201-N11)

This is the corrected practice final for Mathematics for Computer Science, 201-N11, the mathematics course taken at CEGEP by students in computer science programs: ten exercises, one hundred marks, covering the main themes of the course. Boolean logic, number systems, sets and relations, graphs and matrices, modular arithmetic, induction and recursion, counting and probability.

The format is that of a final exam: a Part A that checks the basics chapter by chapter, and a Part B that crosses the topics in synthesis problems. Exercise 8 collects the five most expensive mistakes of the term, one for each family of chapters.

Every question is fully corrected, with the reasoning, the numerical check and an explanation of the mistake the question was designed to provoke. Take it under real conditions, in 150 minutes and without a calculator, before reading the solutions.

10 corrected exercises • 100 points • 150 minutes

This chapter is part of 201-N11, every chapter with its set and sheet

Self-checking set Type your answers and check them question by question: the page tells you right or wrong before you open the solution. With an account, every answer right on the first try earns points, and your right answers stay filled in when you come back.

Course recap

  • • LOGIC: P⇒QP\Rightarrow Q is equivalent to its CONTRAPOSITIVE Q‾⇒P‾\overline{Q}\Rightarrow\overline{P}, never to its converse. The negation of a quantified statement swaps “for every” and “there exists” and negates the property.
  • • NUMBER SYSTEMS: on nn bits, two's complement represents [−2n−1,2n−1−1][-2^{n-1}, 2^{n-1}-1], and −x-x is obtained by inverting the bits and then adding 1. Binary addition is identical signed and unsigned; only the detection of OVERFLOW differs.
  • • RELATIONS: EQUIVALENCE if reflexive, symmetric and transitive, and its classes form a partition. ORDER if reflexive, antisymmetric and transitive; it is TOTAL only if any two elements are always comparable.
  • • GRAPHS: the (i,j)(i,j) entry of MkM^{k} counts the paths of LENGTH kk from ii to jj. The sum of the out-degrees equals the number of arcs in a directed graph.
  • • CONGRUENCES: aa is invertible modulo nn if and only if gcd⁡(a,n)=1\gcd(a,n)=1. The remainder of a Euclidean division is ALWAYS in [0,n)[0, n), including for a negative dividend.
  • • INDUCTION: base case AND inductive step, the hypothesis having to be used explicitly. For a relation that reaches back two steps, two base cases.
  • • COUNTING: nkn^{k} for lists, n!(n−k)!\frac{n!}{(n-k)!} for arrangements, (nk)\binom{n}{k} for combinations, 2n2^{n} for the subsets of an nn-element set, n(n−1)2\frac{n(n-1)}{2} for pairs.
  • • COSTS: graph traversal in O(V+E)O(V+E); a BALANCED binary search tree in log⁡2n\log_{2}n, but LINEAR if it degenerates; the collision threshold of a table of NN slots is reached at about 1.18N1.18\sqrt{N} keys.

Part A: the basics (/50)

Exercise 1: Boolean logic: from truth table to circuit

This practice final covers the chapters of the course in order. We start with logic, on which everything else depends: a circuit, a condition in a program and a proof all obey the same laws.

00011110000111101100110000110011CDAB
  • a) On the Karnaugh map in the figure, identify the two blocks of four cells and give the simplified expression of ff.
  • b) Write the complete disjunctive normal form (canonical sum of products) of ff, before simplification, and count its terms.
  • c) Give the truth table of ff as a function of AA and CC alone, and name the corresponding gate.
  • d) Write the negation of the statement “for every user uu, there is a file ff such that uu can read ff”.
  • e) Is the implication P⇒QP\Rightarrow Q equivalent to Q⇒PQ\Rightarrow P? To Q‾⇒P‾\overline{Q}\Rightarrow\overline{P}? Justify with a truth table.

Type your answers, the page tells you right or wrong 0/12

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) f=A‾ C‾+ACf = \overline{A}\,\overline{C} + AC: BB and DD disappear
  • b) Eight terms of four literals, that is 32 literals, against 4 after simplification
  • c) f=A⊙C=A⊕C‾f = A \odot C = \overline{A \oplus C}, the XNOR gate
  • d) There EXISTS a user uu such that FOR EVERY file ff, uu cannot read ff
  • e) No to the converse, YES to the contrapositive: both equal 0 only on the row PP true, QQ false
a)

The first block gathers the four cells where A=0A=0 and C=0C=0, that is minterms 0, 1, 4 and 5: it gives the term A‾ C‾\overline{A}\,\overline{C}. The second gathers the cells where A=1A=1 and C=1C=1, minterms 10, 11, 14 and 15: it gives ACAC. In both blocks, BB and DD take every value, so they DISAPPEAR. Hence f=A‾ C‾+ACf=\overline{A}\,\overline{C}+AC. Both blocks of four are shaded in the figure.

b)

The complete disjunctive normal form lists one term for each row equal to 1 in the table, that is EIGHT terms of four literals each: A‾ B‾ C‾ D‾+A‾ B‾ C‾D+A‾BC‾ D‾+A‾BC‾D+AB‾CD‾+AB‾CD+ABCD‾+ABCD\overline{A}\,\overline{B}\,\overline{C}\,\overline{D}+\overline{A}\,\overline{B}\,\overline{C}D+\overline{A}B\overline{C}\,\overline{D}+\overline{A}B\overline{C}D+A\overline{B}C\overline{D}+A\overline{B}CD+ABC\overline{D}+ABCD. The simplification in part a) took us from 8 terms of 4 literals to 2 terms of 2 literals, that is from 32 literals to 4: this is exactly what the saving in gates of a circuit measures.

c)

The function depends only on AA and CC: it equals 1 when A=C=0A=C=0 and when A=C=1A=C=1, that is when AA and CC are EQUAL, and 0 otherwise. This is the XNOR gate, also called the equivalence or coincidence gate. We write f=A⊙C=A⊕C‾f=A\odot C=\overline{A\oplus C}, where ⊕\oplus is the exclusive or.

d)

The negation swaps the quantifiers and negates the predicate: “there EXISTS a user uu such that FOR EVERY file ff, uu can NOT read ff”. In other words, at least one user cannot read any file. The rule is mechanical: every “for every” becomes “there exists”, every “there exists” becomes “for every”, and the final property is negated. Skipping a single swap produces a statement that has nothing to do with the original.

e)

P⇒QP\Rightarrow Q is NOT equivalent to its converse Q⇒PQ\Rightarrow P: with PP true and QQ false, the first is false and the second is true. It IS equivalent to its contrapositive Q‾⇒P‾\overline{Q}\Rightarrow\overline{P}, as the table shows: both equal 0 only when PP is true and QQ is false, and 1 in the other three cases. This is what justifies proof by contrapositive, and it is also why confusing the converse with the contrapositive is the most expensive mistake in logic.

00011110000111101100110000110011CDAB

Tick the exercises you have done or want to review: a free account, no password, keeps your ticks and your right answers from one visit to the next, tells you which chapter to tackle next and lets you ask for the exercise you are missing. Create your space, an email is enough.

Exercise 2: Number systems: bases, two's complement and overflow

A computer only knows strings of bits, and the interpretation we give them decides everything. Two's complement is the convention that lets us subtract without any extra circuit.

01234567-8-7-6-5-4-3-2-1binary code 0000 to 1111read in two's complement
  • a) Convert 202 to binary on 8 bits, then to hexadecimal.
  • b) Write −75-75 in two's complement on 8 bits, then give its hexadecimal value.
  • c) On the wheel in the figure, explain what happens when we add 1 to 0111.
  • d) Compute 100+50100+50 on 8-bit signed integers and say what happens.
  • e) Why does the same binary addition work for signed and unsigned numbers, while overflow is not detected in the same way?

Type your answers, the page tells you right or wrong 0/14

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 202=110010102=CA16202 = 11001010_{2} = \mathrm{CA}_{16}
  • b) −75=101101012=B516-75 = 10110101_{2} = \mathrm{B5}_{16}, whose unsigned reading is 181=256−75181 = 256-75
  • c) 0111=+70111 = +7 becomes 1000=−81000 = -8: signed overflow, not flagged by the addition
  • d) The pattern 1001011010010110 is 150 unsigned, −106-106 signed: overflow, since 150>127150 > 127
  • e) Addition modulo 2n2^{n} is the same; it is the RANGES that differ, [0,255][0, 255] and [−128,127][-128, 127]
a)

Successive divisions by 2: 202=128+64+8+2202=128+64+8+2, so 202=110010102202=11001010_{2}. For hexadecimal, we group the bits in nibbles of four: 11001100 is C and 10101010 is A, so 202=CA16202=\mathrm{CA}_{16}. Check: 12×16+10=20212\times 16+10=202 ✓. Going through hexadecimal saves recounting every bit.

b)

First write 75=01001011275=01001011_{2}, since 75=64+8+2+175=64+8+2+1. INVERT every bit: 1011010010110100. ADD 1: 1011010110110101. This is −75-75 in two's complement, that is B516\mathrm{B5}_{16}, or 181 if it were read as an unsigned number. Check: 181+75=256=28181+75=256=2^{8} ✓, which is the very definition of two's complement.

c)

01110111 is +7+7, the largest positive value on 4 bits. Adding 1 gives 10001000, which is −8-8 and not +8+8: the sign bit has turned on. On the wheel, we have gone from the highest position of the positive half-circle to the first position of the negative half-circle, crossing the only discontinuity of the scale. This is a signed OVERFLOW, and the binary addition did not flag it.

d)

100=01100100100=01100100 and 50=0011001050=00110010. Their binary sum is 1001011010010110, which is 150150 unsigned but −106-106 in two's complement, since 150−256=−106150-256=-106. So there is a signed OVERFLOW: the exact result, 150, exceeds the largest representable value, 127. We detect it from the fact that two POSITIVE operands produced a result with a negative sign, which no carry out indicates here.

e)

Because two's complement is designed for exactly that: addition modulo 2n2^{n} is the same operation whichever way we read the codes, and only the NAME given to the codes changes. Overflow, on the other hand, means leaving the representable RANGE, and that range differs: [0,255][0, 255] unsigned, [−128,127][-128, 127] signed. So we detect it with the carry out for unsigned numbers, and with the unexpected change of sign for signed numbers. A processor computes both flags at the same time and lets the program pick the one that matters to it.

01234567-8-7-6-5-4-3-2-1binary code 0000 to 1111read in two's complement

Exercise 3: Sets, relations and partitions

An equivalence relation cuts a set into disjoint pieces; an order relation organizes it into a hierarchy. Knowing which one we are looking at saves us from hunting for properties that do not exist.

  • a) On E={0,1,…,8}E=\{0,1,\dots,8\}, define xRyx\mathcal{R}y when xx and yy have the same remainder modulo 3. Check that this is an equivalence relation and give its classes.
  • b) How many subsets does EE have? How many have exactly 3 elements?
  • c) Verify the inclusion-exclusion principle for ∣A∪B∣\left|A\cup B\right|, where AA is the set of multiples of 2 in EE and BB the set of multiples of 3 in EE.
  • d) Is the relation “divides” on EE without 0 an order relation? Is it total?
  • e) In what sense are a PARTITION and an EQUIVALENCE relation two ways of saying the same thing?

Type your answers, the page tells you right or wrong 0/12

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Three classes: {0,3,6}\{0,3,6\}, {1,4,7}\{1,4,7\} and {2,5,8}\{2,5,8\}
  • b) 29=5122^{9} = 512 subsets, of which (93)=84\binom{9}{3} = 84 have three elements
  • c) 5+3−2=6=∣A∪B∣5+3-2 = 6 = \lvert A \cup B \rvert
  • d) Yes, it is an order, but a PARTIAL one: 2 and 3 are not comparable
  • e) The classes of an equivalence form a partition, and every partition defines an equivalence
a)

REFLEXIVE: every xx has the same remainder as itself ✓. SYMMETRIC: if xx and yy have the same remainder, so do yy and xx ✓. TRANSITIVE: if xx and yy have the same remainder and so do yy and zz, then xx and zz do too ✓. So this is an equivalence relation, and its classes are the three sets {0,3,6}\{0,3,6\}, {1,4,7}\{1,4,7\} and {2,5,8}\{2,5,8\}, corresponding to the remainders 0, 1 and 2.

b)

EE has 9 elements, so 29=5122^{9}=512 subsets, each element being either in or out. The subsets with exactly 3 elements number (93)=9×8×76=84\binom{9}{3}=\frac{9\times 8\times 7}{6}=84. We check consistency with the sum of the binomial coefficients of row 9, which is indeed 512.

c)

A={0,2,4,6,8}A=\{0,2,4,6,8\} has 5 elements, B={0,3,6}B=\{0,3,6\} has 3, and A∩B={0,6}A\cap B=\{0,6\}, the multiples of 6, has 2. So ∣A∪B∣=5+3−2=6\left|A\cup B\right|=5+3-2=6, and we check directly: A∪B={0,2,3,4,6,8}A\cup B=\{0,2,3,4,6,8\}, six elements ✓. Without the subtraction, we would count 0 and 6 twice.

d)

REFLEXIVE: every integer divides itself ✓. ANTISYMMETRIC: if aa divides bb and bb divides aa with a,b>0a,b>0, then a=ba=b ✓. TRANSITIVE: if aa divides bb and bb divides cc, then aa divides cc ✓. So it is an ORDER relation, but it is NOT total: 2 and 3 are not comparable, since neither divides the other. We call it a PARTIAL order, and it is the most common situation in computer science, for example for dependencies between modules.

e)

These are two descriptions of the same object, and we can pass from one to the other in both directions. From an equivalence relation, the CLASSES form a partition: they are non-empty, pairwise disjoint, and their union is EE. From a partition, we define a relation by declaring two elements equivalent when they lie in the same piece, and we check that it is reflexive, symmetric and transitive. The three properties of an equivalence thus correspond exactly to the three properties of a partition, which explains why none of them can be dropped.

Exercise 4: Graphs and matrices: counting paths

The adjacency matrix is not just a table: its powers count paths, and that is what turns a graph problem into a matrix computation.

ABCDEadjacency matrixA01100B00110C00010D00001E10000ABCDE
  • a) On the figure, read off the out-degree of each vertex and check their sum.
  • b) What does the (i,j)(i,j) entry of M2M^{2} count? Illustrate with the path from AA to DD.
  • c) How many paths of length 2 start at AA? List them.
  • d) Does the graph have a cycle? Which one, and of what length?
  • e) What does the matrix M+M2+M3+M4M+M^{2}+M^{3}+M^{4} represent for a graph with 5 vertices?

Type your answers, the page tells you right or wrong 0/13

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Out-degrees 2,2,1,1,12,2,1,1,1, with sum 7, the number of arcs
  • b) It counts the paths of length 2; from AA to DD it equals 2, through BB and through CC
  • c) Three: A→B→CA\to B\to C, A→B→DA\to B\to D and A→C→DA\to C\to D
  • d) Yes: A→B→C→D→E→AA\to B\to C\to D\to E\to A, Hamiltonian of length 5, and A→C→D→E→AA\to C\to D\to E\to A of length 4
  • e) REACHABILITY: a non-zero entry signals a path, and the Boolean version is the transitive closure
a)

From the displayed matrix: AA points to BB and CC, degree 2; BB to CC and DD, degree 2; CC to DD, degree 1; DD to EE, degree 1; EE to AA, degree 1. Sum of the out-degrees: 2+2+1+1+1=72+2+1+1+1=7, which is indeed the number of EDGES (arcs) of the graph. In a directed graph, this sum always equals the number of arcs, and not twice that number as in the undirected case.

b)

The (i,j)(i,j) entry of M2M^{2} is ∑kMikMkj\sum_{k}M_{ik}M_{kj}: each term equals 1 if and only if there is an arc from ii to kk AND an arc from kk to jj. The sum therefore counts the PATHS OF LENGTH 2 from ii to jj. From AA to DD: through BB, since A→B→DA\to B\to D ✓, and through CC, since A→C→DA\to C\to D ✓. The entry is therefore 2.

c)

The paths of length 2 starting at AA first go through BB or CC. From BB: A→B→CA\to B\to C and A→B→DA\to B\to D. From CC: A→C→DA\to C\to D. Total: THREE paths. This is the sum of the row of AA in M2M^{2}, and we can compute it without writing the whole matrix, by adding the out-degrees of the successors of AA, that is 2+1=32+1=3.

d)

Yes: A→B→C→D→E→AA\to B\to C\to D\to E\to A is a cycle of length 5 through every vertex, that is a Hamiltonian cycle. There is a second, shorter one: A→C→D→E→AA\to C\to D\to E\to A, of length 4. A graph with a cycle has no topological sort, which rules out using it as a dependency graph between modules, for example.

e)

Its (i,j)(i,j) entry counts the total number of paths of length 1, 2, 3 or 4 from ii to jj. Such an entry is non-zero if and only if there is a path from ii to jj, because in a graph with 5 vertices, any path with no repeated vertex has at most 4 arcs. This matrix therefore lets us read REACHABILITY, and its Boolean version is the transitive closure of the graph.

Exercise 5: Modular arithmetic: congruences and the affine cipher

The affine cipher is the simplest of the substitution ciphers. It fits entirely in a multiplication modulo 26, and its decryption in a modular inverse.

  • a) Compute 2026 mod 262026\bmod 26 and −45 mod 26-45\bmod 26.
  • b) The affine cipher sends the letter of rank xx to y=5x+8 mod 26y=5x+8\bmod 26. Encrypt the letter M, of rank 12.
  • c) Why is the coefficient 5 suitable and not 13? Give the general criterion.
  • d) Compute the inverse of 5 modulo 26, then write the decryption function.
  • e) Decrypt the letter of rank 3 and check consistency with part b.

Type your answers, the page tells you right or wrong 0/13

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 2026 mod 26=242026 \bmod 26 = 24 and −45 mod 26=7-45 \bmod 26 = 7
  • b) y=68 mod 26=16y = 68 \bmod 26 = 16: M becomes Q
  • c) We need gcd⁡(a,26)=1\gcd(a,26)=1; 5 works, 13 does not, which leaves 12 coefficients out of 26
  • d) 5−1=215^{-1} = 21 modulo 26, and x=21y+14 mod 26x = 21y + 14 \bmod 26
  • e) x=25x = 25, and encrypting does give 3 back
a)

2026=26×77+242026=26\times 77+24, so 2026 mod 26=242026\bmod 26=24. For −45-45: the remainder must be non-negative, so we take q=−2q=-2 and −45=26×(−2)+7-45=26\times(-2)+7, hence −45 mod 26=7-45\bmod 26=7. The reflex −45=26×(−1)−19-45=26\times(-1)-19 would give −19-19, which is not a valid remainder.

b)

y=5×12+8=68y=5\times 12+8=68, and 68=26×2+1668=26\times 2+16, so y=16y=16. The letter of rank 12 is M, the letter of rank 16 is Q: M becomes Q. We always reduce AFTER the addition, never between the two operations, which is allowed because congruence is compatible with both operations.

c)

The coefficient must be INVERTIBLE modulo 26, that is coprime to 26. We have gcd⁡(5,26)=1\gcd(5,26)=1 ✓, so 5 is suitable. On the other hand gcd⁡(13,26)=13\gcd(13,26)=13: with 13, the function x↦13x+8x\mapsto 13x+8 is not injective, it sends all the letters to only two values, and the message becomes undecipherable even for its recipient. CRITERION: aa is suitable if and only if gcd⁡(a,26)=1\gcd(a,26)=1, which leaves 12 possible coefficients out of 26.

d)

We look for uu such that 5u≡1(mod26)5u\equiv 1\pmod{26}. By trial: 5×21=105=26×4+15\times 21=105=26\times 4+1 ✓, so the inverse is 21. Decryption: from y=5x+8y=5x+8 we get 5x=y−85x=y-8, then x=21(y−8) mod 26x=21\left(y-8\right)\bmod 26. We can expand: x=21y−168x=21y-168, and −168 mod 26=14-168\bmod 26=14 since −168=26×(−7)+14-168=26\times(-7)+14, so x=21y+14 mod 26x=21y+14\bmod 26.

e)

x=21×3+14=63+14=77x=21\times 3+14=63+14=77, and 77=26×2+2577=26\times 2+25, so x=25x=25. Check by encrypting: 5×25+8=1335\times 25+8=133, and 133=26×5+3133=26\times 5+3 ✓, we do get 3 back. The two functions are therefore inverses of each other, which is exactly what the invertibility of 5 modulo 26 guarantees.

Part B: problems and reasoning (/50)

Exercise 6: Induction: a complete proof

The induction exercise is the one where the most marks are lost, and for reasons of writing. Here we ask for a complete proof, with both steps named and the hypothesis used explicitly.

  • a) Prove that 13+23+⋯+n3=(n(n+1)2)21^{3}+2^{3}+\dots+n^{3}=\left(\frac{n(n+1)}{2}\right)^{2} for every n≥1n\geq 1.
  • b) What do you notice when you compare this result with the sum of the first nn integers?
  • c) Prove that 7n−17^{n}-1 is divisible by 6 for every n≥0n\geq 0.
  • d) Prove that the sequence defined by u0=2u_{0}=2 and un+1=un2+1unu_{n+1}=\frac{u_{n}}{2}+\frac{1}{u_{n}} satisfies un≥2u_{n}\geq\sqrt 2 for every nn.
  • e) Link part d to an algorithm seen in the course.

Type your answers, the page tells you right or wrong 0/13

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) True at n=1n=1, and (k(k+1)2)2+(k+1)3=((k+1)(k+2)2)2\left(\frac{k(k+1)}{2}\right)^{2}+(k+1)^{3} = \left(\frac{(k+1)(k+2)}{2}\right)^{2}
  • b) The sum of the cubes is the SQUARE of the sum of the integers, Nicomachus's identity
  • c) 7k+1−1=7(7k−1)+6=6(7m+1)7^{k+1}-1 = 7(7^{k}-1)+6 = 6(7m+1)
  • d) uk+1−2=(uk−2)22uk≥0u_{k+1}-\sqrt2 = \dfrac{(u_{k}-\sqrt2)^{2}}{2u_{k}} \ge 0
  • e) NEWTON's method on f(x)=x2−2f(x)=x^{2}-2: u1=1.5u_{1}=1.5, u2≈1.41667u_{2}\approx 1.41667, u3≈1.414216u_{3}\approx 1.414216
a)

BASE CASE at n=1n=1: on the left 13=11^{3}=1, on the right (1×22)2=1\left(\frac{1\times 2}{2}\right)^{2}=1 ✓. INDUCTIVE STEP: suppose the formula holds for kk. Then the sum for k+1k+1 is (k(k+1)2)2+(k+1)3=k2(k+1)2+4(k+1)34=(k+1)2(k2+4k+4)4=(k+1)2(k+2)24=((k+1)(k+2)2)2\left(\frac{k(k+1)}{2}\right)^{2}+(k+1)^{3}=\frac{k^{2}(k+1)^{2}+4(k+1)^{3}}{4}=\frac{(k+1)^{2}\left(k^{2}+4k+4\right)}{4}=\frac{(k+1)^{2}(k+2)^{2}}{4}=\left(\frac{(k+1)(k+2)}{2}\right)^{2} ✓. The hypothesis was used to replace the sum of the first kk cubes, and the decisive step is factoring out (k+1)2(k+1)^{2}. Check at n=4n=4: 1+8+27+64=1001+8+27+64=100 and (4×52)2=102=100\left(\frac{4\times 5}{2}\right)^{2}=10^{2}=100 ✓.

b)

The sum of the cubes is the SQUARE of the sum of the integers: 13+⋯+n3=(1+2+⋯+n)21^{3}+\dots+n^{3}=\left(1+2+\dots+n\right)^{2}. This is a remarkable identity, often attributed to Nicomachus, and it is far from obvious: nothing in the definition of cubes announces that they add up to a perfect square. It also gives an instant check: the sum of the cubes is always a perfect square.

c)

BASE CASE at n=0n=0: 70−1=07^{0}-1=0, divisible by 6 ✓. INDUCTIVE STEP: suppose 7k−1=6m7^{k}-1=6m. Then 7k+1−1=7×7k−1=7(7k−1)+7−1=7×6m+6=6(7m+1)7^{k+1}-1=7\times 7^{k}-1=7\left(7^{k}-1\right)+7-1=7\times 6m+6=6\left(7m+1\right) ✓. The trick is to write 7×7k7\times 7^{k} as 7(7k−1)+77\left(7^{k}-1\right)+7, so as to force the expression for kk to appear. We could also have concluded directly by congruence: 7≡1(mod6)7\equiv 1\pmod 6 so 7n≡17^{n}\equiv 1.

d)

BASE CASE: u0=2≥2≈1.414u_{0}=2\geq\sqrt 2\approx 1.414 ✓. INDUCTIVE STEP: suppose uk≥2u_{k}\geq\sqrt 2, so uk>0u_{k}>0. We study uk+1−2=uk2+1uk−2=uk2−22 uk+22uk=(uk−2)22uku_{k+1}-\sqrt 2=\frac{u_{k}}{2}+\frac{1}{u_{k}}-\sqrt 2=\frac{u_{k}^{2}-2\sqrt 2\,u_{k}+2}{2u_{k}}=\frac{\left(u_{k}-\sqrt 2\right)^{2}}{2u_{k}}. The numerator is a square, hence non-negative, and the denominator is strictly positive: the difference is non-negative, so uk+1≥2u_{k+1}\geq\sqrt 2 ✓. Recognizing a perfect square is what makes the proof immediate.

e)

This is exactly NEWTON's method applied to f(x)=x2−2f(x)=x^{2}-2, whose iteration is un+1=12(un+2un)u_{n+1}=\frac{1}{2}\left(u_{n}+\frac{2}{u_{n}}\right), which is the given relation. Part d proves that the sequence stays above the root from the very first step, which is the property observed in the chapter on recursion: the error en+1=en22une_{n+1}=\frac{e_{n}^{2}}{2u_{n}} is always positive. Computations: u1=1.5u_{1}=1.5, u2≈1.41667u_{2}\approx 1.41667, u3≈1.414216u_{3}\approx 1.414216, against 2≈1.414214\sqrt 2\approx 1.414214.

Exercise 7: Counting, probability and the binary search tree

A binary search tree turns a list into a logarithmic structure. Counting it, analyzing it and comparing it with a sequential search draws on three chapters at once.

50307020406080
  • a) On the tree in the figure, give the path followed to search for the key 40 and count the comparisons.
  • b) What is the height of this tree, and how many keys can a binary tree of height hh hold at most?
  • c) How many comparisons are needed at most in a balanced tree of 1000 keys? Compare with sequential search.
  • d) The keys 20, 30, 40, 50, 60, 70, 80 are inserted in this increasing order. What shape does the tree take, and what is the search cost then?
  • e) The seven keys are inserted in a randomly drawn order. What is the probability of getting the degenerate shape of part d (a linked list whose keys all go to the same side)?

Type your answers, the page tells you right or wrong 0/14

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 50→30→4050 \to 30 \to 40, three comparisons
  • b) Height 2, and a tree of height hh holds at most 2h+1−1=72^{h+1}-1 = 7 keys: it is perfectly full
  • c) 11 comparisons against 1000, about 91 times fewer
  • d) The tree degenerates into a linked list of height 6: the cost becomes linear again
  • e) 25040=12520≈0.04 %\dfrac{2}{5040} = \dfrac{1}{2520} \approx 0.04\,\%: the worst case is very rare on random data
a)

We start at the root 50: 40<5040<50, so we go left to 30. Then 40>3040>30, so we go right to 40. Finally 40=4040=40, found. The path is 50→30→4050\to 30\to 40 and it cost THREE comparisons, against seven in the worst case of a sequential search on the seven keys. The path is highlighted in the figure.

b)

The tree in the figure has height 2, counting the root at level 0. A binary tree of height hh holds at most 2h+1−12^{h+1}-1 keys, since level kk holds at most 2k2^{k} and ∑k=0h2k=2h+1−1\sum_{k=0}^{h}2^{k}=2^{h+1}-1. Here 23−1=72^{3}-1=7 ✓, the tree is PERFECTLY full. We recognize the formula of the Towers of Hanoi, which is no accident: both count a structure that doubles at every level.

c)

A balanced tree of nn keys has a height of about log⁡2n\log_{2}n, so we need at most log⁡2(1000)+1≈10.97\log_{2}(1000)+1\approx 10.97, that is 11 comparisons. Sequential search would need up to 1000, about 91 times more. This is the same gain as binary search, which makes sense: a balanced binary search tree IS a binary search laid out in memory.

d)

Each new key being larger than all the previous ones, it systematically goes right: the tree DEGENERATES into a linked list of height 6. The search cost becomes LINEAR again, up to 7 comparisons. This is the worst case of the structure, and it occurs precisely on data that is already sorted, a frequent situation in practice. This is what motivates automatically balanced trees, such as red-black trees.

e)

There are 7!=50407!=5040 possible insertion orders, all equally likely. Exactly one gives the strictly increasing chain, and exactly one the strictly decreasing chain, that is 2 degenerate orders in this sense. The probability is therefore 25040=12520≈0.0004\frac{2}{5040}=\frac{1}{2520}\approx 0.0004, about 0.04 percent. The worst case is thus extremely rare on random data, which explains why the AVERAGE height of a randomly built tree is of order 1.39log⁡2n1.39\log_{2}n, very close to the optimum. We find exactly the trade-off of quicksort: a catastrophic but unlikely worst case.

50307020406080

Exercise 8: Five claims to correct

Each of the following five claims is FALSE. Say why and give the correct statement. They sweep across the chapters of the course.

  • 1) “P⇒QP\Rightarrow Q and Q⇒PQ\Rightarrow P are equivalent, since implication is symmetric.”
  • 2) “On 8 bits, 100+50100+50 is 150, so there is no problem.”
  • 3) “The divides relation on the positive integers is a total order.”
  • 4) “−45 mod 26-45\bmod 26 is −19-19.”
  • 5) “A binary search tree guarantees logarithmic search time.”

Type your answers, the page tells you right or wrong 0/10

1)
2)
3)
4)
5)
Show the solution

Answers

  • 1) FALSE: it is the CONTRAPOSITIVE that is equivalent, not the converse
  • 2) FALSE when signed: the pattern is −106-106, there is overflow. The claim only holds unsigned
  • 3) FALSE: it is a PARTIAL order, since 2 and 3 are not comparable
  • 4) FALSE: −45 mod 26=7-45 \bmod 26 = 7. In C or Java, we correct with ((a % n)+n) % n((a\,\%\,n)+n)\,\%\,n
  • 5) FALSE without an assumption of BALANCE: on sorted keys, the tree degenerates and the search becomes linear
1)

FALSE, implication is not symmetric. P⇒QP\Rightarrow Q is false in the single case PP true and QQ false, whereas Q⇒PQ\Rightarrow P is false in the symmetric case: they therefore differ on two of the four rows. What IS equivalent to P⇒QP\Rightarrow Q is its CONTRAPOSITIVE Q‾⇒P‾\overline{Q}\Rightarrow\overline{P}. Example: “if it rains, the ground is wet” does not imply “if the ground is wet, it rains”.

2)

FALSE if we work with SIGNED INTEGERS. On 8 signed bits, the representable range is [−128,127][-128, 127], and 150 exceeds it: the resulting bit pattern, 1001011010010110, reads as −106-106. So there is a silent OVERFLOW. The claim is only correct for unsigned numbers, where the range goes up to 255. Specifying the convention is not a vocabulary detail, it is what decides the result.

3)

FALSE, it is a PARTIAL order. It is indeed reflexive, antisymmetric and transitive, but it is not TOTAL: 2 and 3 are not comparable, since neither divides the other. A total order requires any two elements to be always comparable, which is the case for the usual order but rarely for the orders that come up in computer science, such as dependencies between tasks.

4)

FALSE. Euclidean division requires 0≤r<260\leq r<26, so −19-19 is not a valid remainder. We take q=−2q=-2: −45=26×(−2)+7-45=26\times(-2)+7, so −45 mod 26=7-45\bmod 26=7. This is also what Python returns. In C or Java, the operator does give −19-19, but it does not compute the Euclidean remainder: we then have to correct it with ((a % n)+n) % n((a\ \%\ n)+n)\ \%\ n.

5)

FALSE without an assumption of BALANCE. If the keys are inserted in increasing order, the tree degenerates into a linked list and the search becomes linear again, with nn comparisons instead of log⁡2n\log_{2}n. The logarithmic guarantee only exists for trees that are kept balanced, such as red-black trees or AVL trees. With RANDOM insertions, the average height stays close to 1.39log⁡2n1.39\log_{2}n, but an average is not a guarantee.

Exercise 9: Synthesis problem: storing passwords

Designing how a site stores its passwords draws on hashing, modular arithmetic, counting and probability. It is the problem that best brings the course together.

1002003004005006007008000.10.20.30.40.50.60.70.80.91table of 65,536 slotsnumber of keysprobability of a collision
  • a) Why are passwords never stored in plain text, or even encrypted in a reversible way?
  • b) A hash table has 65,53665{,}536 slots. The figure gives the probability of at least one collision as a function of the number of keys. Recover the 50 percent threshold by computation.
  • c) The site has 200,000 users. How many accounts per slot on average, and what can we say about the most heavily loaded slot?
  • d) An attacker has stolen the table of hashes. He tries every 8-letter lowercase password at 101010^{10} attempts per second. How long does he need? What does adding a random SALT for each user change?
  • e) Summarize in three rules what this problem demands of the designer.

Type your answers, the page tells you right or wrong 0/13

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) A leak would hand over every account, and the key of a reversible encryption would be stolen along with the database: we need a one-way function
  • b) 1.1865,536=1.18×256≈3021.18\sqrt{65{,}536} = 1.18 \times 256 \approx 302 keys, a fill rate below 0.5 %0.5\,\%
  • c) 3.053.05 accounts per slot on average, and at least 4 in the most heavily loaded one: collisions are unavoidable
  • d) About 21 seconds without salt; with one salt per user, the work must be redone for each, about 48 days
  • e) Store only hashes, salt for each user, and choose a SLOW function of the bcrypt or Argon2 kind
a)

Because a leak of the database would immediately hand over every account, and not only those of the site: users reuse their passwords elsewhere. REVERSIBLE encryption is no better, since the decryption key is necessarily present on the server and will be stolen along with everything else. Only a one-way function will do, that is a hash function: the server verifies by recomputing the hash, without ever being able to go back to the password.

b)

With N=65,536N=65{,}536 slots, the 50 percent threshold is reached at about 1.18N=1.18×256≈3021.18\sqrt{N}=1.18\times 256\approx 302 keys. The figure confirms it: the curve crosses 0.50.5 just after 300. The result is striking, 302 keys in 65,536 slots are enough, a fill rate below half of one percent. This is the birthday paradox applied to hashing.

c)

200,00065,536≈3.05\frac{200{,}000}{65{,}536}\approx 3.05 accounts per slot on average. The PIGEONHOLE principle guarantees that at least one slot holds at least ⌈3.05⌉=4\left\lceil 3.05\right\rceil=4 of them, which is a very weak bound; in practice, with a good hash function, the most heavily loaded slot holds a dozen. The important conclusion is that collisions are UNAVOIDABLE, so the structure must handle overflow lists.

d)

268=208,827,064,576≈2.09×101126^{8}=208{,}827{,}064{,}576\approx 2.09\times 10^{11}, so about 2121 seconds to exhaust the space. Without salt, this effort breaks EVERY account at once, since the same password gives the same hash everywhere, and the attacker can even settle for a precomputed table. With a random SALT for each user, the hash depends on the account: the attacker has to redo the 21 seconds FOR EACH user, that is about 48 days for 200,000 accounts, and no precomputed table is of any use. Salt does not make a weak password stronger, it prevents the attack from being shared across accounts.

e)

ONE, only ever store hashes, produced by a one-way function. TWO, salt every password with a random value specific to the user, to prevent any shared attack or precomputed-table attack. THREE, choose a SLOW, tunable hash function, of the bcrypt or Argon2 kind, so that the 101010^{10} attempts per second of part d drop to a few thousand. These three rules depend on no particular technology, they follow directly from the counting in this course.

1002003004005006007008000.10.20.30.40.50.60.70.80.91table of 65,536 slots302 keysnumber of keysprobability of a collision

Exercise 10: Synthesis problem: analyzing a network

The last problem, the one that ties together graphs, recursion and cost. A network of machines is modelled by a graph, and almost every operational question is a question about traversal.

  • a) A network has 5 machines connected by the links of the graph of exercise 4. Can EE be reached from AA? Give a path.
  • b) How many links would be needed for every pair to be directly connected, in an undirected network of 5 machines? And of 100 machines?
  • c) We want to detect whether the network contains a cycle. Describe an algorithm and give its cost.
  • d) A depth-first traversal is naturally recursive. What are its two termination conditions on a graph, and what happens if we forget the second?
  • e) On a network of 100 machines and 300 links, compare the cost of a depth-first traversal with that of a naive test of all paths.

Type your answers, the page tells you right or wrong 0/13

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Yes: A→B→D→EA \to B \to D \to E, or A→C→D→EA \to C \to D \to E
  • b) (52)=10\binom{5}{2} = 10 and (1002)=4950\binom{100}{2} = 4950: the number grows like the square
  • c) Depth-first traversal with three states, and an arc to a vertex IN PROGRESS signals a cycle: cost O(V+E)O(V+E)
  • d) A base case, and the MARKING that makes the remaining work decrease; without it, the recursion loops on a cycle
  • e) 400 operations against the order of 99!99!: a change of nature, from linear to factorial
a)

Yes. The path A→B→D→EA\to B\to D\to E works, of length 3, and so does A→C→D→EA\to C\to D\to E. We can check it on the matrix: the entry of M3M^{3} at the corresponding position is non-zero. Since the arc E→AE\to A also exists, the two machines are mutually reachable and therefore belong to the same strongly connected component.

b)

In an undirected network, linking every pair takes (n2)=n(n−1)2\binom{n}{2}=\frac{n(n-1)}{2} links. For n=5n=5: 5×42=10\frac{5\times 4}{2}=10 links. For n=100n=100: 100×992=4950\frac{100\times 99}{2}=4950. The number grows like the SQUARE of the number of machines, which makes a full mesh impractical beyond a few hundred nodes and explains the use of hierarchical topologies.

c)

We run a DEPTH-FIRST traversal, marking each vertex with one of three states: unvisited, in progress, finished. If we meet an arc leading to a vertex that is IN PROGRESS, we have found a cycle. The traversal visits each vertex once and examines each arc once, so its cost is O(V+E)O(V+E), linear in the size of the graph. This is also the algorithm that produces a topological sort when no cycle is found.

d)

The two conditions are to have a BASE CASE, here a vertex with no unvisited successor, and to make the amount of remaining work DECREASE, which is ensured by MARKING the vertices already seen. If we forget the marking, the recursion runs forever as soon as the graph contains a cycle, since we keep passing through the same vertices. This is exactly the second termination condition of the chapter on recursion, transposed to graphs: the argument must get closer to the base case.

e)

DEPTH-FIRST TRAVERSAL: O(V+E)=100+300=400O(V+E)=100+300=400 elementary operations, a matter of a microsecond. NAIVE TEST of all paths: the number of simple paths can reach the order of 99!99!, a number with 156 digits, completely out of reach. The ratio is not a factor but a change of nature, from linear to factorial. This is the general lesson of the course: the right data structure and the right traversal turn an impossible problem into a trivial one, and no hardware makes up for choosing a bad algorithm.

Something missing from this set? A type of exercise your teacher gives, a problem you are stuck on, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Exercise set published at www.letuteurscientifique.ca/en/exercices/cegep-n11-practice-final. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

See also

Looking for a math tutor for computer science in Montreal?

Get in touch for a first session. We prepare for the final exam at the real level of the test, chapter by chapter and then under exam conditions.

Site by Studio Squalli