Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'pre increment' a BigInteger in Java?

I have a for loop with BigIntegers, something like this:

for(BigInteger a = BigInteger.valueOf(1); a.compareTo(someBigInteger); ++a) {...

Obviously I can't use the ++ operator on a non-primitive. How do I work around this?

Also, I have to use BigInteger in this scenario.

like image 524
Andreas Hartmann Avatar asked Feb 01 '15 15:02

Andreas Hartmann


People also ask

How do you increment a BigInteger?

You can have it like this. for(BigInteger a = BigInteger. ONE; a. compareTo(someBigInteger); a=a.

How do you add two big integers in 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.


1 Answers

++a is a prefix increment, not a postfix increment, but in the context of a for-loop it doesn't really matter, as you ignore the return value of that statement anyway. In any event, this functionality could be acheieved by calling BigInteger.add. Also note that compareTo returns an int, and since Java does not have implicit casts between ints and booleans (like, e.g., C does), you'd have to compare its result to 0 to see if a is smaller, larger or equal to someBigInteger):

for (BigInteger a = BigInteger.ONE; 
     a.compareTo(someBigInteger) < 0; 
     a = a.add(BigInteger.ONE)) {...
like image 115
Mureinik Avatar answered Oct 28 '22 17:10

Mureinik