Solved problem 24 in scala