Problem 17 solution (need to make more elegant)