CSC310 02 Algorithm Correctness
CSC310 02 Algorithm Correctness
Lecture Notes
Dr Fatimah Adamu-Fika
Department of Cyber Security
Faculty of Computing
Air Force Institute of Technology
Kaduna, Nigeria
April 2022
© Since 2020. All rights reserved. No part of this document may be reproduced or
transmitted in any form or by any means, electronic or mechanical, including
photocopy, recording, or any information storage and retrieval system, without
permission in writing from the author.
CONTENT
Overview................................................................................................................................... 1
Unit Goals................................................................................................................................20
Exercises ..................................................................................................................................21
Textbooks ............................................................................................................................25
Websites ..............................................................................................................................25
Supposing time and space are not major constraints for algorithms, we still need to
study algorithms. Because we would like to ascertain that given legitimate input, our
algorithm terminates with the correct solution within a finite amount of time. However,
we can accept an algorithm that is often correct, i.e., even if fails to produce the
correct result always, there is still control on how often it produces wrong solutions. For
example, Rabin-Miller Primality Test (used in the RSA algorithm) doesn’t always
produce correct results. 1 out of 250 times it gives an incorrect result. Correctness can
be tricky with another class of algorithms, which do not find exact solutions but rather
find near-optimal ones. By “near-optimal,” we typically mean that the quantitative
measure of the solution found by the algorithm is within some known factor of the
optimal solution’s quantitative measure. This desired factor is specified beforehand,
and we can say that a correct solution from an approximation algorithm is any
solution that is within that factor of the optimal solution. That is, for an approximation
algorithm we typically would like to show that the error produced by the algorithm
does not exceed a predefined limit. These types of algorithms are called
approximation algorithms and they are used in optimisation problems.
Consequently, we need to prove our algorithm is correct. Logically, we can test the
correctness of sample input instances. However, testing may not find obscure
(hidden) bugs, as such, it can be dangerous. An alternative method that can be used
alongside testing is a mathematical method called correctness proof. This involves
proving the correctness of the algorithms via mathematical methods. The most
common one used in verifying algorithms is called mathematical induction.
For example,
1 + 3 + 5 + … + (2n – 1) = n2
This asserts that the sum of consecutive odd numbers from 1 to (2n – 1) is given by the
formula on the right. We want to prove that this is true for n = 1, n = 2, n = 3, and so
on. Now we can check the formula for any specific value of n, for example, n = 5:
1 + 3 + 5 + 7 + 9 = 25 = 52
1 + 3 + 5 + 7 + 9 + 11 = 36 = 62
However, it would be impossible to check for every possible value of n. So, how do
we prove this rule for every value of n? We show that the statement is true for n = 1.
We then show that if the statement is true for any specific number k, (e.g., 21), then it
will be true for its successor (the next number), k + 1, (e.g., 22). Since the statement is
true when n = 1, it then follows that the statement is true for n = 1 + 1 = 2. Therefore,
it will be true for n = 2 + 1 =3, for n = 3 + 1 = 4, for n = 4 + 1 = 5, etc. Continuing in this
If
and
2. when a statement is true for n = k, then it will also be true for its successor, n =
k + 1;
1. S1 is true;
2. for any positive integer k, n ≥ k, if Sk is true, then Sk+1 is also true;
Let S be the set of integers n for which a propositional function Pn is true. The basis of
mathematical induction verifies that 1 ∈ S. The inductive step shows that k ∈ S implies
k + 1 ∈ S. Thus, therefore the principle of mathematical induction proves S = ℕ. It
follows that Pn is true for all integers n ≥ 1.
P1 ⟹ P2 ⟹ P3 ⟹ P4 ⟹ …
We can compare induction to climbing an infinite ladder, when we climb the bottom
(first) rung, it makes it possible for us to climb the second rung. Climbing the second
rung in turn makes it possible to climb the third. Eventually, we can climb up as high
as we want. However, this will not happen unless these conditions are met:
• We must be able to climb unto the first rung. This is the basis.
The distance between adjacent rungs must be set up correctly. Otherwise, the next
rung may be too high for us to reach. Maintaining the right inter-rung distance ensures
that Pk ⇒ Pk +1 for each rung (integer) k ≥ 1. This is the induction step. To prove the
implication Pk ⇒ Pk + 1, we first assume Pk is true, then using it we prove Pk + 1 is also
Another analogy we can use to understand induction is the domino effect. Suppose
that we have infinitely many dominoes arranged in a line. When we make the first
domino falls, it will in turn make the second fall, the second will knock the third and so
on. Eventually, all our dominoes will fall. However, this will not happen unless these
conditions are met:
When we use mathematical induction, we must take care to be precise with our
assumptions.
• We say the assumption “holds for some integer k ≥ 1.” We DO NOT assume it
“holds for all integers k ≥ 1.” If we already know the statement holds true for all
k ≥ 1, then there is no need to prove it.
• Be sure to specify the requirement k ≥ 1. In our ladder-climbing metaphor
above, this ensures that we start climbing from the lowest rung.
• We are assuming that the statement is true when “n equals k”, and using it to
show that the statement holds true when “n equals k + 1”, thus we DO NOT say
“let n = k” or “let n = k + 1.” Saying “let” denotes assignment, it means we are
assigning the value of k and k + 1 to n.
Example 1. Prove that the sum of the first positive odd numbers is given by the
formula:
1 + 3 + 5 + … + (2n – 1) = n2
Let’s assume Sn = the sum of the first n odd numbers greater than 0.
Step 1:
First, we will show that the formula is true for the first odd number, n = 1.
LHS = 2 ⋅ 1 – 1 = 1
RHS = 12 = 1
LHS = RHS
S1 holds true.
Step 2:
Sk: 1 + 3 + 5 + … (2k – 1) = k2
Assuming this induction hypothesis, we must then prove that the formula is true for the
successor of k, k + 1, that is for n = k + 1.
To do that we simply add the next term after k (successor of k) to both sides of the
induction hypothesis. By definition of Sn, the next term following k is the next odd
number in the sequence, which will be (2(k + 1) – 1) = (2k + 1).
= k2 + 2k + 1
= k2 + k + k + 1
= (k + 1)(k + 1)
= (k + 1)2
This shows that Sk+1 = (k + 1)2 holds true. We have now fulfilled both conditions of the
principle of mathematical induction. So, we can conclude that since S1 = 1 and that
Sk ⟹ Sk+1 then Sn is equal to the sum of the first n odd numbers for all n > 0. That is, the
formula is true for every natural number.
We can use the summation notation (also called the sigma notation) to abbreviate a
sum. For example, the sum in Example 1 above can be written as:
𝑛
∑(2𝑖 – 1) = 𝑛2
𝑖=1
The letter i is the index of summation. By putting i = 1 under ∑ and n above, we declare
that the summation starts with i = 1, and ranges through i = 2, i = 3, i = 4 and so on,
until we reach i = n. The quantity that follows ∑ describes the pattern of terms that
we are adding in the summation.
Accordingly,
𝑛
∑(2𝑖 – 1) = (2 × 1 – 1) + (2 × 2 – 1) + (2 × 3 – 1)
𝑖=1
In general, the sum of the first n terms in a sequence, {ai, a2, a3, …} is denoted by
∑𝑛𝑖=1 𝑎𝑖 . Observe that in an induction proof, the link between Sk+1 and Sk is provided
by:
∑ 𝑎𝑖 = (∑ 𝑎𝑖 ) + 𝑎𝑘+1
𝑖=1 𝑖=1
1(1 + 1)(2 ⋅ 1 + 1)
12 =
6
LHS = 1
1⋅2⋅3 6
𝑅𝐻𝑆 = = =1
6 6
LHS = RHS
Inductive Step: We now show that if the proposition holds for k, then the proposition
holds for k + 1.
Pk+1 = Pk + (k + 1)2
𝑘+1 𝑘
∑ 𝑖 2 = (∑ 𝑖 2 ) + (𝑘 + 1)2
𝑖=1 𝑖=1
𝑘 (𝑘 + 1)(2𝑘 + 1)
= + (𝑘 + 1)2
6
𝑘 (𝑘 + 1)(2𝑘 + 1) + 6(𝑘 + 1)2
=
6
𝑘 (2𝑘 + 1) + 6(𝑘 + 1)
= (𝑘 + 1) [ ]
6
2𝑘 2 + 7𝑘 + 6
= (𝑘 + 1) [ ]
6
2𝑘 2 + 4𝑘 + 3𝑘 + 6
= (𝑘 + 1) [ ]
6
2𝑘(𝑘 + 2) + 3(𝑘 + 2)
= (𝑘 + 1) [ ]
6
(𝑘 + 2)(2𝑘 + 3)
= (𝑘 + 1) [ ]
6
(𝑘 + 1)(𝑘 + 2)(𝑘 + 3)
=
6
Conclusion: Therefore, the identity also holds when n = k + 1. This completes the
induction.
Even though the basis often starts with n = 1, this is not necessarily true for all cases, it
may begin with n = 0 and possibly with any fixed natural number n = N, establishing
the truth of the statement for all natural numbers n ≥ N. Some statements Pn are not
true for the first few values of n, but are true for all values of n greater than or equal to
some fixed integer n0. This means that in the base step, we can start with n being any
integer n0, n = n0.
The major difference is in the basis step: we need to verify that 𝑃𝑛0 is true. Also, in the
inductive hypothesis, we need to emphasise that k ≥ n0. Thus, the principle can be
formally defined as:
Let n0 be any integer, and let Pn be a proposition (about integers) such that 𝑃𝑛0 is true,
and for each n ≥ n0, if Pk holds for some integer k such that k ≥ n0 then so does Pk+1 ;
then Pn holds for all integers n ≥ n0.
Inductive Step: We will show that if the proposition holds for n = k, then the proposition
holds for n = k + 1.
Pk + 1 = Pk + 1 + 4k + 1
𝑘+1 𝑘
∑ 4𝑖 = (∑ 4𝑖 ) + 4𝑘+1
𝑖=0 𝑖=0
1
= (4𝑘+1 – 1) + 4𝑘+1
3
1
= [(4𝑘+1 – 1) + 3 ⋅ 4𝑘+1 ]
3
1
= [(4𝑘+1 – 1) + (4 − 1) ⋅ 4𝑘+1 ] [“3” is the same thing as “4 – 1”]
3
1
= [4𝑘+1 – 1 + 4 ⋅ 4𝑘+1 – 4𝑘+1 ]
3
1
= [4 ⋅ 4𝑘+1 + 4𝑘+1 – 4𝑘+1 – 1] [rearranging the equation gives us]
3
1
= [41 ⋅ 4𝑘+1 – 1] [“4” is the same thing as “41”]
3
1
= [4(𝑘+1)+1 – 1]
3
1 𝑘+2
= [4 – 1]
3
Conclusion: Therefore, the identity also holds when n = k + 1. This completes the
induction.
Besides identities, there are two other broad proposition structures that can be proved
by induction, divisibility and inequality propositions.
P1: 51 – 21 = 5 – 2 = 3, is divisible by 3.
Inductive Step: We will show that if the proposition holds for n = k, then the proposition
holds for n = k + 1.
Induction hypothesis: We assume the claim holds when n = k for some integer n ≥ 1.
Pk: 5k – 2k is divisible by 3.
Pk + 1: 5k + 1 – 2k + 1 is divisible of 3.
To show that the claim holds for Pk+1 holds, we need to make use of 5k – 2k = 3q from
the induction hypothesis. This means we need to connect the expression 5k + 1 – 2k + 1
to the expression 5k – 2k. Now, we proceed with our proof.
5k + 1 – 2k + 1 = 5 . 5k – 2 . 2k [laws of exponents]
= 3 . 5k + 2 . 5k – 2. 2k (5a = 3a + 2a)
= 3 . 5k + 2 . (5k – 2k)
= 3 . (5k + 2q)
Example 5. Use mathematical induction to show that nn ≥ 2n, for all integers n ≥ 2.
LHS = 22 = 2 × 2 = 4
RHS = 22 = 2 × 2 = 4
LHS = RHS
Inductive Step: We will show that if the proposition holds for n = k, then the proposition
holds for n = k + 1.
Pk: kk ≥ 2k
Proof:
≥ 2k+1
Thus,
∴ (k + 1)k+1 ≥ 2k+1
Conclusion: Therefore, the inequality still holds when n = k + 1. This completes the
induction.
Base case : We show that inequality holds for the base case.
LHS = 4! = 4 × 3 × 2 × 1 = 24
RHS = 24 = 2 × 2 × 2 × 2 = 16
Inductive Step: We will show that if the proposition holds for n = k , then the proposition
holds for n = k + 1.
Pk: k! ≥ 2k.
Proof:
≥ 2 ⋅ 2k [since k ≥ 4, ∴ k +1 ≥ 5 >2]
Thus
(k + 1)! ≥ 2k ⋅ (k + 1) ≥ 2 ⋅ 2k
∴ (k + 1)! ≥ 2k+1
Conclusion: Therefore, the inequality still holds when n = k + 1. This completes the
induction.
Sometimes in an induction proof, it is hard to show that Pk implies Pk+1. It may be easier
to show some “lower” Pm (with m = k) implies Pk+1. For such situations, there is a slight
variant of induction called strong induction, in which we assume that the statement
holds for all values preceding k. This provides us with more information to use when
trying to prove the statement.
Strong Induction
Strong induction is quite similar to regular induction. However, there is a difference in
the induction hypothesis. Normally, in standard induction, we assume that Pk is true to
prove that Pk+1. In strong induction, we assume that all of P1, P2, P3, …, Pk are true to
prove Pk+1. Returning to our domino effect analogy above. Suppose that we still have
infinitely many dominoes arranged in a line. However, this time, the weight of the kth
domino is not enough to knock down the (k + 1)th domino. Knocking down the (k +
1)th domino required the weight of all the dominoes before it. Even with this additional
constraint, we can prove that all the dominoes will fall if we are able to knock down
the first domino. Thus, in standard induction the induction hypothesis is Pk , and the
inductive step consists in proving that Pk ⟹ Pk+1. Whereas in strong induction the
induction hypothesis is 𝑃𝑛0 ∧ 𝑃𝑛0 +1 ∧ 𝑃𝑛0+2 ∧ … ∧ Pk, and the induction step consists in
proving that 𝑃𝑛0 ∧ 𝑃𝑛0 +1 ∧ 𝑃𝑛0 +2 ∧ … ∧ Pk ⟹ Pk+1. This variant is called strong induction
because we use more statements in the induction hypothesis.
To prove that a proposition function Pn is true for all integers n ≥ n0, follow the following
steps:
Let n0 be any integer, and let Pn be a proposition (about integers) such that 𝑃𝑛0 is true
for each n ≥ n0, if Pk holds for all integers k such that n0 ≤ k ≤ n then so does Pk+1; then
Pn holds for all integers n ≥ n0.
Base case: We show the proposition holds for the base case(s).
When n = 1:
a1 = 3 ⋅ 21–1 + 2(–1)1
LHS = a1 = 1
∴ LHS = RHS
When n = 2:
LHS = a2 = 8
∴ LHS = RHS
Inductive Step: Let k ∈ ℤ+ with k ≥ 3 given and assume the proposition is true for n = 1,
2, 3, …, k, then ak+1 = ak + 2ak–1.
Induction hypothesis: For the strong inductive hypothesis, suppose that for some k ≥ 3
we assume that am = 3 ⋅ 2m–1 + 2(–1)m for all 1 ≤ m ≤ k.
ak+1 = 3 ⋅ 2k + 2(–1)k+1
Proof:
ak+1 = ak + 2ak–1
= 3 ⋅ 2𝑘 + 2 (– 1)𝑘+1
Conclusion:
Hence, by the Principle of Strong Induction, we have an = 3 ⋅ 2n–1 + 2(–1)n for all n ∈
ℤ +.
1. ∑𝑛𝑖=1 2𝑖 = 𝑛(𝑛 + 1)
1
2. ∑𝑛𝑖=1(2𝑖) 2 = 3 2𝑛(𝑛 + 1)(2𝑛 + 1)
3. The sum of the square of the first 2n positive integers for all n ≥ 1 is given by:
𝑛(2𝑛+1)(4𝑛+1)
∑2𝑛 2
𝑖=1 𝑖 = .
3
We will be doing a lot of strong induction proofs to check our algorithms that are
recursive in nature. For those that are iterative in nature, we are going to prove their
correctness by induction on their loop invariants.
• Prove it by induction on the “size” of the problem being solved (e.g., size (or
length) of an array, number of bits in an integer, etc).
• The base of recursion is the base of induction.
• Inductive step: Assume that the recursive calls work correctly and use this
assumption to prove that the current call works correctly.
• Need to prove that recursive calls are given sub-problems, i.e., no infinite
recursion (often trivial).
Now, let's prove the correctness of our recursive algorithms from our algorithm
examples in Unit 1.
Recursive POW2(n)
Claim:
Basis:
Induction hypothesis:
RTP:
Proof:
= 2k+1
Conclusion:
Recursive EVENSUM(n)
Claim:
Basis:
Induction hypothesis:
RTP:
EVENSUM(k) + (2 (k + 1) – 2)
= ∑𝑘+1
𝑖=1 (2𝑖 – 2)
Conclusion:
Recursive FIB(n)
Claim:
Basis:
Induction hypothesis:
RTP:
FIB(k) + FIB(k – 1)
= Fk+1
Conclusion:
1. Analyse the algorithm one loop at a time, starting at the innermost loop in case
of nested loops.
2. For each loop devise a loop invariant that remains true through each iteration
of the loop and captures the “progress” made by the loop.
3. Prove that the loop invariants hold.
4. Use the loop invariants to prove that the algorithm terminates.
5. Use the loop invariants to prove that the algorithm computes the correct result.
Loop Invariants
An invariant is a statement about program vari-ables that is true every time the
execution of the program reaches the invariant. A loop invariant is a statement about
program variables that is true before and after each iteration of a loop. Knowing the
invariant(s) of the loop is essential in understanding its effect.
1. Initialisation: The loop invariant must be true before the first execution of
the loop.
3. Termination: The loop terminates. And when the loop is terminated, the loop
invariant, along with the reason that the loop terminated, gives us a useful
property. That is, the loop invariant should tell us something useful that shows
the algorithm is correct, i.e., something that helps us understand the algorithm.
A loop invariant is usually placed at the beginning of the loop. A well-chosen loop
invariant is useful both when designing, testing, and modifying code. It also serves as
documentation and can be the foundation of correctness proof.
For example, let’s consider our iterative EVENSUM(n) algorithm in Unit 1, we can
place a loop invariant at the start of the loop, before any other statements. This
invariant will assert the value of the variable at every execution of the loop:
1. while( i ≤ n )
2. //Invariant: even = 0 + 2 + 4 + … + (2i – 2)
3. even = even + (2i – 2)
4. i=i+1
2. Supposing the invariant hold true before the ith iteration, it will also hold true
after this iteration since the loop adds 2i – 2 to even and increment by one.
even = 0 + 2 + 4 + … + (2i – 2), this is exactly what’s required for the algorithm
to be correct.
You will notice the three steps above, constitute an induction proof, which shows
when the program leaves the loop even = 0 + 2 + 4 + … + (2i – 2).
Notation
To explain how induction on loop variants works, we will look at our simple one-loop
iterative algorithms in the examples above. The value in identifier j immediately after
the kth iteration of the loop is denoted jk (k = 0 means immediately before entering
the loop for the first time). For example, j8 denotes the value of the identifier j after 8th
time around the loop.
Iterative POW2(n)
Claim:
Let’s find a pattern as the programme variables in POW2(n) change from one
iteration of the loop to the next.
i0 = 1, i1 = 1, i2 = 2, i3 = 3 …
Thus, ik = k
Thus, powerk = 2k
Basis:
When n = 0
So, power0 = 20 = 1.
Induction hypothesis:
Proof:
ik+1 = ik + 1
powerk+1 = 2 × powerk
= 2k+1
Conclusion:
Claim:
Termination:
Since ik+1 = ik + 1, eventually i will be equal n and the loop will terminate.
Suppose this happens after t iterations. Since it = n and it = t [∵ ik = k ], we can
conclude that t = n [∵ it = n = t].
Results:
powert = 2t = 2n [∵ t = n].
Note that the proof by induction is the initialisation and maintenance phase of the
loop invariant.
Iterative EVENSUM(n)
Claim:
To determine the loop invariants let’s for EVENSUM(n), let’s find a pattern of
its programme variables within the loop through each execution of the
loop.
i0 = 1 = 0 + 1, i1 = 2 = 1 + 1, i2 = 3 = 2 + 1 …
Thus, ik = k + 1
even0 = 0
= ∑𝑘𝑖=1(2𝑖 – 2)
Basis:
When n = 1
[Trivial is a solution that is simple and of little interest. Often, solutions or examples
involving 0 are considered trivial. Non-zero solutions or examples are
considered non-trivial. For example,3x + y = 0 has the trivial solution x = 0, y =
0]
Induction hypothesis:
RTP:
Proof:
ik+1 = ik + 1
=k+2
Conclusion:
Claim:
Since ik+1 = ik + 1, eventually i will equal n + 1 and the loop will terminate.
Assume this happens after iterations. Since it = n + 1 and it = t + 1 [∵ ik = k +
1], we can conclude that t = n [∵ it = n + 1 = t + 1].
Results:
Note that the proof by induction is the initialisation and maintenance phase of the
loop invariant.
Iterative FIB(n)
Claim:
i0 = 2 = 0 + 2, ii = 3 = 1 + 2,
i2 = 4 = 2+ 2, i3 = 5 = 3 + 2, …
Thus, ik = k + 2
a0 = 0 = F0, a1 = b0 = 1 = F1,
a2 = b1 = 1 = F2, a3 = b2 = 2 = F3, ….
Thus, ak = Fk
Thus, bk = Fk+1
Basis:
Induction hypothesis:
RTP:
ik+1 = ik + 1
=k+3
ak+1 = bk
bk+1 = fibk+1
= ak + bk
= Fk+2
Conclusion:
Claim:
Termination:
Since ik+1 = ik + 1, eventually i will equal n + 1 and the loop will terminate.
Suppose this happens after t iterations. Since it = n + 1 and it = t + 2, we can
conclude that t = n – 1.
Results:
Note that the proof by induction is the initialisation and maintenance phase of the
loop invariant.
UNIT GOALS
1. Using recursion solves these problems and proof they are correct.
a. Computing the nth factorial.
b. Finding the maximum number in a list of numbers.
c. Computing the greatest common divisor.
2. Solve these problems using non-recursive methods and proof their solutions are
correct.
a. Computing the nth factorial.
b. Finding the maximum number in a list of numbers.
c. Multiplying two square matrices of integers.
3. Write pseudocode for linear search, which scans through a list, looking for a
value. Using loop invariants, prove that your algorithm is correct. Make sure that
your loop invariant fulfils the three necessary properties.
4. The two algorithms below are both intended to calculate the factorial of any
positive integer n. For example, if n = 5, the algorithm should calculate the
factorial of 5 and return 120, from 1 × 2 × 3 × 4 × 5.
I.
Algorithm Factorial(n)
Input: n, a natural number
Output: factorial, the factorial of n (n!)
START
1. factorial = 1
2. i = 1
3. while( i ≤ n )
4. factorial = factorial – i
5. i=i +1
6. return factorial
END
II.
Algorithm Factorial(n)
Input: n, a natural number
Output: factorial, the factorial of n (n!)
START
1. factorial = 1
2. i = 1
3. while( i ≤ n )
4. factorial = factorial * i
5. i=i + 1
6. return factorial
END
Which statements best describe the behaviour of the algorithms?
a. Algorithm (I) calculates the correct factorial, but algorithm (II) does not.
b. Algorithm (II) calculates the correct factorial, but algorithm (I) does not.
c. Both algorithms calculate the correct factorial.
d. Neither algorithm calculates the correct factorial.
For example, for the given list [“hello”, “world!”, “black&white”], it should return
the number 2 since two of the three strings in the list contain disallowed
characters.
Algorithm ReportDisallowed(S)
Input: S, an array of strings
Output: haDisallowed, number of strings that have disallowed
characters.
START
1. haDisallowed = 0
2. for( i = 0; i < S.length; i++ )
3. if( S[i] contains “!” OR S[i] contains “&” )
4. haDisallowed = haDisallowed + 1
5. return haDisallowed
6. return haDisallowed
END
A programmer tests the procedure with various inputs and finds multiple cases
where it does not produce the expected output.
Which calls to ReportDisallowed([…]) will return an incorrect number?
a. ReportDisallowed([“gov&politics”, “h1st0ry”, “l1t3r@ture”])
b. ReportDisallowed([“b!ology”, “ch3m1stry”, “physics”])
c. ReportDisallowed([“@lgebra”, “log&exp”, “factorials!”])
d. ReportDisallowed([“algor!thm-analysis”, “arrays&lists”, “complex1ty”])
9. The goal of the procedure longestWord is to return the longest word in a given
list of words. For example, if it's given the list [“superhero”, “captain”, “marvel”] ,
it should return “superhero” as the longest word.
Algorithm LongestWord(S)
Input: S, an array of strings
Output: longWord, the longest word in array S.
START
1. longWordLen = 0
2. longWord = “”
3. for( i = 0; i < S.length; i++ )
4. if( S[i].length > longWordLen )
5. longWord = S[i]
6. longWordLen = S[i].length
7. return longWord
8. return longWord
END
A programmer tests the algorithm with various inputs and finds that there are
multiple cases where it does not produce the expected output.
Which calls to LongestWord([…]) do not actually return the longest word?
a. LongestWord([“computer”, “phone”, “tablet”])
b. LongestWord([“triangle”, “circle”, “square”])
c. LongestWord([“pear”, “banana”, “pineapple”])
d. LongestWord([“blue”, “purple”, “red”])
10. The two algorithms below are both intended to calculate the product of
squares from 1 to n, where n is any positive integer. For example, if n is 3, the
algorithms should calculate a product of 36, from 12 × 22 × 33.
I.
Algorithm ProductSquare(n)
Input: n, a natural number
Output: product, the product of squares from 1 to n
START
1. product = 0
2. i = n
3. while( i > 0 )
4. product = product * ( i * i )
5. i = i – 1
6. return product
END
II.
Algorithm ProductSquare (n)
Input: n, a natural number
Output: product, the product of squares from 1 to n
START
1. product = 1
2. i = 0
Textbooks
[1] A. Levitin, Introduction to the Design and Analysis of Algorithms, Boston: Pearson,
2012.
Websites