Chapter 3, Exercise 6 (Better solution, adapted from sample solution)