correct but slow solution for exercise 16.  Will have to optimize to meet 5 min time limit