Skip to content
Advertisement

Calculate average of a huge long array

I’m trying to calculate the average of many (more than 200) long (primitive type) values stored in an array. Usually you add all the numbers and divide it by the number of the values. But this is not possible in this case since there is no primitive datatype in Java capable of holding such a large number, isn’t it? Will java.math.BigInteger help here?

Advertisement

Answer

Yes it will help you. An BigInteger can be as big as you want. Till there is not enough RAM.

With BigInteger bigInt = BigInteger.valueOf(long); you can convert the Long to an BigInteger.

And an BigInteger is immutable. So if you divide it like this bigInt = bigInt.divide(BigInteger.valueOf(200)); You have to reassign it.

A more precise option would be the method BigInteger.divideAndRemainder().

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement