Solution to Problem 4. Slow but works.