Sometimes it is not large enough.
A more serious issue is that often arithmetic operations need to be exact.
Recall that 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 calculations are needed.
The Advance Encryption Standard (the most commonly used cipher),
uses keys up to 256 bits in length.
Ordinary arithmetic with int
s is not going to work.
You could write your own methods where an integer is represented with array of int
s.
Addition could be done by adding corresponding elements of two arrays.
Logic would be needed to deal with
overflow from one element into the next higher element.
But, conveniently, the Java BigInteger
class already has what you need.
BigInteger
implements immutable integers of unlimited magnitude.
They can be as big or as negative as you need.
Here is an example program:
BigInteger
documentation at Oracle:
BigInteger
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
Notes:
1. BigInteger
is a class (not a primitive type). Big integers are represented as objects.
2. import java.math.BigInteger
to use the class.
3. The BigInteger
objects are immutable. The value of a BigInteger
object does not change,
although a BigInteger
reference variable can point to different objects as needed.
4. Arithmetic operations (and other operations) are implemented as methods of the class.
5. The usual operators (+, -, *, /
) will not work. Use methods add, subtract, multiply, divide.
6. The result of using add, subtract, multiply, divide
methods is another BigInteger
.
7. The constructor used here takes a String
of decimal digits representing an integer of any size.
The String
is converted into the internal representation used by BigInteger
.
8. The toString()
method of BigInteger
is invoked when needed (as in the last statement above.)
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 );