Problem 10: complete solution. (slow, some minutes)