Scala algorithms to math problems