Java中的大数

Java中的大数,java,numbers,integer,biginteger,Java,Numbers,Integer,Biginteger,在Java中,我将如何使用非常大的数字进行计算 我尝试了long,但最大值为9223372036854775807,当使用整数时,它没有保存足够的数字,因此不够精确,无法满足我的需要 还有其他方法吗?您可以使用biginger类来表示整数,使用BigDecimal来表示十进制数字。这两个类都是在java.math包中定义的 例如: BigInteger reallyBig = new BigInteger("1234567890123456890"); BigInteger notSoBig =

在Java中,我将如何使用非常大的数字进行计算

我尝试了
long
,但最大值为9223372036854775807,当使用整数时,它没有保存足够的数字,因此不够精确,无法满足我的需要


还有其他方法吗?

您可以使用
biginger
类来表示整数,使用
BigDecimal
来表示十进制数字。这两个类都是在
java.math
包中定义的

例如:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);

签出
BigDecimal
biginger
使用作为Java库一部分的
biginger


下面是一个很快就能得到大数字的例子

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

根据您所做的工作,您可能想看看GMP(gmplib.org),它是一个高性能的多精度库。要在Java中使用它,需要在二进制库中使用JNI包装器

请参阅一些Alioth Shootout代码,了解使用它而不是BigInteger来计算任意位数的Pi的示例


如果您计划使用BigInteger类进行计算,可能值得一提的是(虽然我想这对大多数人来说很明显)使用BigInteger类会对继承性能造成影响。@haylem性能速度是一样的,但数字的长度需要时间。他们使用位运算符进行计算。就像在对基本类型进行数学运算时通常发生的情况一样。
9223372036854775807
Long.MAX_value
的精确值。对于非常大的斐波那契数,递归计算非常耗时。使用起来更好。几个Math.pow()和Math.sqrt()之后,就完成了!:)@然而,ZubinMukerjee在BigDecimal上的pow和sqrt也不便宜。它比迭代好,但不像听起来那么简单。
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));
    }
}