Incredibly slow solution for problem 5