Solved #5 in scala