Solves Problem 24 in Python