Problem 24
Ugly solution for Problem 27
Problem 40