Problem 9

I solved problem 9, but I would like to improve the efficiency a little bit. It took almost 9 seconds on my i3.