Solution for problem 32, not entirely efficient, but it will do.