Fixed algorithm
Solved problem 49 in scala