104

How would I go about doing calculations with extremely large numbers in Java?

I have tried long but that maxes out at 9223372036854775807, and when using an integer it does not save enough digits and therefore is not accurate enough for what I need.

Is there anyway around this?

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Petey B
  • 11,439
  • 25
  • 81
  • 101

6 Answers6

170

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package.

Example:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Fabio Vinicius Binder
  • 13,024
  • 4
  • 34
  • 33
  • 11
    Might be worth mentioning the (though obvious for most, I guess) inherit performance hit incurred by the use of the BigInteger class if you plan to do calculations with that. – haylem Feb 29 '12 at 00:43
  • @haylem the performance speed is the same but the length of the number makes it takes time. they use bitwise operators to do the calculations. like what happens normally when doing math with primitive types. – Eboubaker Aug 20 '19 at 11:29
22

Use the BigInteger class that is a part of the Java library.

http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
AlbertoPL
  • 11,479
  • 5
  • 49
  • 73
18

Here is an example which gets big numbers very quickly.

import java.math.BigInteger;

/*
250000th fib # is: 36356117010939561826426 .... 10243516470957309231046875
Time to compute: 3.5 seconds.
1000000th fib # is: 1953282128707757731632 .... 93411568996526838242546875
Time to compute: 58.1 seconds.
*/
public class Main {
    public static void main(String... args) {
        int place = args.length > 0 ? Integer.parseInt(args[0]) : 250 * 1000;
        long start = System.nanoTime();
        BigInteger fibNumber = fib(place);
        long time = System.nanoTime() - start;

        System.out.println(place + "th fib # is: " + fibNumber);
        System.out.printf("Time to compute: %5.1f seconds.%n", time / 1.0e9);
    }

    private static BigInteger fib(int place) {
        BigInteger a = new BigInteger("0");
        BigInteger b = new BigInteger("1");
        while (place-- > 1) {
            BigInteger t = b;
            b = a.add(b);
            a = t;
        }
        return b;
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    For really large Fibonacci numbers, the recursive calculation is ridiculously time consuming. Much better to use [Binet's explicit formula](http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html). A few Math.pow()s and Math.sqrt()s later, you're done! :) – Zubin Mukerjee Oct 06 '16 at 16:35
  • 2
    @ZubinMukerjee however pow and sqrt on BigDecimal isn't cheap either. It is better than iteration but not as simple as it sounds. – Peter Lawrey Oct 06 '16 at 16:42
13

Checkout BigDecimal and BigInteger.

soorapadman
  • 4,451
  • 7
  • 35
  • 47
Clint Miller
  • 15,173
  • 4
  • 37
  • 39
6
import java.math.BigInteger;
import java.util.*;
class A
{
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter The First Number= ");
        String a=in.next();
        System.out.print("Enter The Second Number= ");
        String b=in.next();

        BigInteger obj=new BigInteger(a);
        BigInteger obj1=new BigInteger(b);
        System.out.println("Sum="+obj.add(obj1));
    }
}
RobEarl
  • 7,862
  • 6
  • 35
  • 50
Rupendra Sharma
  • 240
  • 4
  • 6
3

Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.

See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.

https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html

igouy
  • 2,547
  • 17
  • 16
Trevor Tippins
  • 2,827
  • 14
  • 10