Very slow solution for problem 50 in scala