Question

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

Was it helpful?

Solution

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)

OTHER TIPS

Compare:

>> val x = 1 to Int.MaxValue
x: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(...)

With:

>> val x = 1L to Int.MaxValue
x: scala.collection.immutable.NumericRange.Inclusive[Long] = NumericRange(...)

Note that the first uses Int.to, and the latter used Long.to (where Int.MaxValue is up-converted automatically). Of course, the sum of a consecutive integer sequence has a very nice discrete formula :)

Happy coding.

This isn't very efficient, but the easiest way:

val x = 1L to Int.MaxValue
println(x.sum) //prints 2305843008139952128

If you need x to contain Ints rather than Longs, you can do

val x = 1 to Int.MaxValue
println(x.foldLeft(0L)(_+_))
Range.Long(1, Int.MaxValue, 1).sum
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top