go to previous page   go to home page   go to next page highlighting

Answer:

Sometimes even it is not large enough.


BigInteger

A more serious issue is that often arithmetic operations need to be exact. Operations with floating point are often not exact. double is represented in 64 bits, so only some numbers in its range can be represented exactly. For number theory, cryptography, and other applications, exact integer calculations are needed.

The Advance Encryption Standard (the most commonly used cipher), uses keys up to 256 bits in length. Ordinary arithmetic with int is not going to work.

One of the constructors for BigInteger accepts a String of digits as an argument. The String can have many digits and is used to construct the BigInteger object (which is not a string.)

Unfortunately, the String of digits cannot include underscores or spaces. It can start with a + or a - character.

You could write your own methods where integers are represented with arrays of ints. Your code could do addition by adding corresponding elements of two arrays. Logic could deal with the carry from from one digit position in the integer into the next higher position. (Remember doing this in 4th grade?) But, conveniently, the Java BigInteger class already has what you need.

BigInteger implements immutable integers of unlimited magnitude. They can be as big as you need, both positive and negative. Here is an example program:


import java.math.BigInteger;

class BigIntAdd
{

  public static void main ( String[] args )
  {
    BigInteger a = new BigInteger( "1000000000" );  
    BigInteger b = new BigInteger( "2000000000" );

    System.out.println("The sum of " + a + " and " + b + " is " + a.add( b ) );
  }
}



The sum of 1000000000 and 2000000000 is 3000000000

QUESTION 4:

What do you imagine is the output of the following?

BigInteger a = new BigInteger( "1" );
BigInteger b = new BigInteger( "2" );
BigInteger c;

c = a.divide( b );
System.out.println( a + "/" + b + " is " + c );

go to previous page   go to home page   go to next page