slow solution for problem 39