Problem 39 solution