Solved problem 39 in scala