solution for problem 10 (very slow solution)