Solution for problem 31, Finally got this one. took too long!