Support Forums
[Tutorial] Java Big Integer Class - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Java Programming (https://www.supportforums.net/forumdisplay.php?fid=22)
+---- Thread: [Tutorial] Java Big Integer Class (/showthread.php?tid=1378)



[Tutorial] Java Big Integer Class - Eustaquio - 10-13-2009

Hi of new!!!

In this thread I'm gonna explain some about Big Integer, nothing out of normal... hehe but you will be able to start opreating with them!!!

Why use them?

Because sometimes you need to save a variable with more digits than LONG have, so you will need BigInteger class...

And also that class has some interesting features like prime numbers, random numbers etc...

First of all wehave to import this class:

Code:
import java.math.*;

Now we have to declare any variable:

Code:
BigInteger a;
BigInteger b = BigInteger.ZERO;
BigInteger c = BigInteger.ONE;
BigInteger d = new BigInteger ("3");
BigInteger e = BigInteger.valueOf(5);

This is like this because you can't convert int/long into BigInteger directly or using

Code:
BigInteger = (BigInteger) 3;

So you have to use valueOf etc...

Now, starting to operate with BigIntegers... there is a method for each operation, add, multiply, substract...

Examples:

Code:
a.multiply(b);
a.add(b);
a.substract(b);
a.divide(b);

Now we have also methods to compare two BigIntegers to see if it is equalsto, less than etc...

Code:
a.compareTo(b); //This returns -1 if it is less than, 0 if are equals and +1 if it's bigger than...

a.equals(b); //Returns if are equals or not

And finally, an exapmle full explained:

Code:
public class multiply {
     public static void main(String[] args) {
        BigInteger total = BigInteger.valueOf(1);
        for(int i = 1; i <= 100; i++)
            total = total.multiply(BigInteger.valueOf(i));
        System.out.println(total);
     }
}

This is an easy code but it's simple to see it when you see it by first time.

See you next time.