Solved problem 5 but it is slow