Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tutorial] Java Big Integer Class
#1
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Java Tutorial United States of America 0 589 01-23-2012, 03:39 PM
Last Post: United States of America
  why java haphazard 8 1,439 12-12-2011, 03:23 AM
Last Post: RDCA
  Need Java help from java expert. Blazin 2 1,903 09-07-2011, 02:43 PM
Last Post: AceInfinity
  Java help php 1 830 04-06-2010, 06:41 AM
Last Post: php
  Java Problem for real java programmer Testgamma1 10 4,485 03-14-2010, 09:08 AM
Last Post: uber1337

Forum Jump:


Users browsing this thread: 1 Guest(s)