Awful solution to problem 32
Slightly optimized solution to problem 32; still a bit ugly