Exercise 12.7 (with an ugly algorithm).