Reduce integer list / range of integers in scala

The general question for beginners is here ... Today, trying to calculate the sum of a list of integers (actually BitSet), I came across overflow scripts and noticed that the return type (sum / product) is Int. Are there any methods in Range / List for summing or multiplying all values ​​by Long?

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

thanks

+4
source share
4 answers

Convert the elements to Long (or BigInt if they go that far), adding up:

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

You can also return to the folder

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

(Note: if you are summing over a range, it might be better to do a little math, but I understand that this is not what you actually did)

+9
source

This is not very effective, but the easiest way:

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

If you need x to contain Ints, not Longs, you can do

 val x = 1 to Int.MaxValue println(x.foldLeft(0L)(_+_)) 
+2
source

For comparison:

 >> 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 former uses Int.to , and the latter used Long.to (where Int.MaxValue is converted automatically). Of course, the sum of a sequential integer sequence has a very good discrete formula :)

Happy coding.

+2
source
 Range.Long(1, Int.MaxValue, 1).sum 
+1
source

Source: https://habr.com/ru/post/1369109/


All Articles