6

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

Ajay
  • 977
  • 2
  • 11
  • 23

4 Answers4

12

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)

Didier Dupont
  • 29,398
  • 7
  • 71
  • 90
3

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.

2

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)(_+_))
soc
  • 27,983
  • 20
  • 111
  • 215
Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
1
Range.Long(1, Int.MaxValue, 1).sum
Landei
  • 54,104
  • 13
  • 100
  • 195