Java 中的大数

如何在 Java 中使用极大的数字进行计算?

我试过使用 long,但它的9223372036854775807是最大的,当使用一个整数时,它没有保存足够的数字,因此对于我需要的数字来说不够精确。

还有别的办法吗?

259017 次浏览

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);

Checkout BigDecimal and BigInteger.

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

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;
}
}

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

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));
}
}