Problem 4 from 52 programming problems book

Solution: