Adapted solution from problem 31