Solution to problem 31 that runs for way too long