Saturday, November 9, 2013

Java: Use BigInteger in for-loop

In my previous post, I mentioned a way to handle large integers by using BigInteger. Now I'm going to provide a very important usage of it. We often use for-loop. So here is the way to use it:

Ordinary integers:
for(int i = 1; i <= n; i++) {
 //Task to do

for (BigInteger bi = BigInteger.valueOf(1);
                bi.compareTo(n) <= 0;
                bi = bi.add(BigInteger.ONE)) {
//Task to do
here n is a BigInteger variable.