Reputation: 398
Friends,
I'm trying to learn Scala coding and exploring the reduce() function as of now. I don't understand why the following piece of code to multiply all numbers in a list give me negative output:
val inputRDD=sc.parallelize(List(1,2,3,3,4,5,6,7,8,9,19,22,21,25,34,56,4,32,56,70))
val result=inputRDD.reduce((x,y)=>x*y)
println(result)`
I get the answer "-1619001344" when i run the above code. If i try using "+" in reduce instead of "*" i get the proper sum, but not otherwise. I also tried converting result to Int, String and Long
Upvotes: 1
Views: 380
Reputation: 8996
The Int and Long types are both overflowing, so you need to use BigInt for this operation.
val inputRDD = sc.parallelize(List(1,2,3,3,4,5,6,7,8,9,19,22,21,25,34,56,4,32,56,70))
val inputRDDasBigInt = inputRDD.map(x => scala.BigInt(x))
val result = inputRDDasBigInt.reduce((x,y)=>x*y)
println(result)
228235320014929920000
Upvotes: 2