Skip to main content

Posts

Showing posts with the label BigInteger

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 } BigInteger: for (BigInteger bi = BigInteger.valueOf(1);                 bi.compareTo(n) <= 0;                 bi = bi.add(BigInteger.ONE)) { //Task to do } here n is a BigInteger variable.

Java: BigInteger

Many of you might have wondered, as I did, how to deal with integers of say more than 50 digits or so. And might have thought about breaking the integer into parts or storing it in a string and parse letter-by-letter . Java provides a class for such large numbers: BigInteger . You can find it in the package: java.math.BigInteger We can do some operations like addition, subtraction, multiplication, division etc, but slightly in a different way. For detailed information on its usage, have a look at this .