Brute force solution to problem 27. Might be improvable.