Compulsory Exercises (Tuesday 13 October 2015)
Exercise 3.1 Consider the square-and-multiply algorithm as given in Table 2. What can you say about this algorithm with respect to Input, Output, Definiteness, Correctness, Finiteness, Effectiveness, and Generality.
Output. The algorithm returns explicitly with a value, and the type and range can be deduced from how it is calculated.
Definiteness. Every line is unambiguous so this is ok.
Correctness. We need to make a proof by mathematical induction to demonstrate this beyond any doubt and this is the topic of next week.
Finiteness. The algorithm terminates immediately if . Otherwise and the algorithm is called recursively for . Hence diminishes for each recursive call and must ultimately reach 1 so that the algorithm is finite.
Effectiveness. About multiplications are needed in the worst case, and it is obviously more efficient than the naïve approach making multiplications. This is the best known algorithm for the purpose.
Generality. Taking the restrictions mentioned under input into account, the algorithm is valid for any values. The proof of induction for correctness will make this clear.
Exercise 3.2 Consider the square-and-multiply algorithm which calculates . Write pseudo code for an iterative version of this algorithm.
Exercise 3.3 Consider the following linear search algorithm:
- procedure find(,)
- for
- if , return
It finds the index of an element in an array . Rewrite the algorithm using recursion instead of a loop.
Exercise 3.4 Give pseudo-code for a recursive version of Euclid’s algorithm, and verify that the properties Input, Output, Definiteness, Correctness, Finiteness, Effectiveness, and Generality.
Exercise 3.5 How many comparisons are needed, in the worst case, to sort an array using
- ... insertion sort.
- ... selection sort.
- ... merge sort.
Compare the three. Is any one faster than the others?
Exercise 3.6 Tabulate the following recurrence for :
Can you spot a pattern? Try to guess a closed form expression.