Suppose List 1 and List 2 are two lists of numbers in increasing order.
(i)Write an algorithm to find elements in List 1 that are not present in List 2.
(ii)Write an algorithm to find elements in List 2 that are not present in List 1.
Answer
(i) Go through the lists together with pointers i (List 1) and j (List 2): if L1[i] < L2[j], L1[i] is not in List 2 — record it and move i; if L1[i] = L2[j], move both; if L1[i] > L2[j], move j. When List 2 ends, record all the remaining elements of List 1.
(ii) The same algorithm with the roles of the two lists exchanged.
Question 2
Describe an algorithm to compute the least common multiple (lcm) of two numbers.
Answer
Method 1: Check the multiples of the larger number m, n, 2m, 3m, … and stop at the first one that is also divisible by the other number — that is the lcm.
Method 2: lcm(m, n) = $\frac{m \times n}{\gcd(m, n)}$; compute the gcd with Euclid’s algorithm, then divide.
Question 3
Divisors occur in pairs, e.g. the divisors of 18 are (1, 18), (2, 9), (3, 6).
(i)If we write out divisors in pairs, how many numbers do we have to examine between 1 and n to find all divisors of n?
(ii)If we list divisors in pairs, will our gcd algorithm still work in the same manner?
Answer
(i) We only need to check numbers from 1 up to $\sqrt{n}$; each divisor d found gives its pair n/d.
(ii) Yes — we get the same set of divisors (just found in pairs), so the gcd algorithm still works; we only need to combine both members of each pair into the list.