Problem 12.

I spent wayyyyy too much time optimizing this one.