Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reduce list of integers/range of integers in scala

Total newbie question here...Today while trying to calculate sum of a list of integers(actually BitSet), I ran into overflow scenarios and noticed that the return type of(sum/product) is Int. Are there any methods in Range/List to sum up or say multiply all values to Long?

val x = 1 to Integer.MaxValue
println(x.sum) //prints -1453759936

thanks

like image 460
Ajay Avatar asked Aug 26 '11 06:08

Ajay


Video Answer


1 Answers

Convert the elements to Long (or BigInt should that go that far) while summing:

x.view.map(_.toLong).sum

You can also go back to fold

x.foldLeft(0L)(_ + _)

(Note: should you sum over a range, maybe it would be better do a little math, but I understand that is not what you did in fact)

like image 180
Didier Dupont Avatar answered Sep 19 '22 12:09

Didier Dupont