Andreas Hartmann Andreas Hartmann - 4 months ago 20
Java Question

How to 'pre increment' a BigInteger in Java?

I have a

for
loop with
BigInteger
s, 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.

Answer

++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 it's 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)) {...
Comments