Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum a list of BigIntegers

I've looked all over but can't figure this out. How do you sum a list of BigIntegers?

Using System.Numerics;
Using System.Linq;

List<BigInteger> bigInts = new List<BigInteger>();
BigInteger sum = bigInts.Sum();             // doesn't work
BigInteger sum = bigInts.Sum<BigInteger>(); // doesn't work
BigInteger sum = bigInts.Sum(x => x);       // doesn't work

Do you have to do this?

BigInteger sum = new BigInteger(0);
foreach(BigInteger bigint in bigInts)
    sum += bigint;
like image 531
jb. Avatar asked Apr 21 '12 04:04

jb.


People also ask

How to sum BigInteger Java?

math. BigInteger. add(BigInteger val) is used to calculate the Arithmetic sum of two BigIntegers. This method is used to find arithmetic addition of large numbers of range much greater than the range of biggest data type double of java without compromising with the precision of the result.

How to add BigInt?

A bigint is created by appending n to the end of an integer literal or by calling the function BigInt that creates bigints from strings, numbers etc.

What is BigInteger zero Java?

The signum() method of Java BigInteger class is used to check whether a BigInteger value is positive, negative or zero. This method returns one of the following values depending on the following conditions : This method returns 1 when this BigInteger is positive. This method returns 0 when this BigInteger is zero.

What is BigInteger one in Java?

BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java. lang. Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.


2 Answers

var sum = bigInts.Aggregate(BigInteger.Add);

Aggregate gets a delegate to a method which gets two BigIntegers and return a BigInteger. It uses a default BigInteger as initial value (0), and goes over each BigInteger, invoking BigInteger.Add with the previous result (0 would be previous result in the first time - also called 'seed') and the current element.

like image 134
SimpleVar Avatar answered Oct 12 '22 10:10

SimpleVar


Aggregate function is more general version of Sum:

var bigInts = new List<System.Numerics.BigInteger>(); 
bigInts.Add(new System.Numerics.BigInteger(1));

var result = bigInts.Aggregate((currentSum, item)=> currentSum + item));
like image 45
Alexei Levenkov Avatar answered Oct 12 '22 11:10

Alexei Levenkov