problem 12 slow but elegant solution