Answers:
您可以将BigInteger
类用于整数和BigDecimal
具有十进制数字的数字。这两个类都在java.math
包中定义。
例:
BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);
使用BigInteger
属于Java库的一部分的类。
http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html
这是一个迅速获得大量数字的例子。
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;
}
}
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));
}
}
根据您的工作,您可能想看看GMP(gmplib.org),它是一种高性能的多精度库。要在Java中使用它,您需要二进制库周围的JNI包装器。
有关使用它代替BigInteger来将Pi计算为任意位数的示例,请参见一些Alioth Shootout代码。
https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html
9223372036854775807
是的确切值Long.MAX_VALUE
。