Java中的大数字

Pet*_*y B 90 java integer numbers biginteger

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

我已经尝试long但最大限度为9223372036854775807,并且当使用整数时,它不能保存足够的数字,因此不够准确,无法满足我的需要.

有没有办法解决?

Fab*_*der 150

您可以将该BigInteger类用于整数和BigDecimal具有十进制数字的数字.这两个类都在java.math包中定义.

例:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);
Run Code Online (Sandbox Code Playgroud)

  • 可能值得一提的是(虽然对于大多数人来说显而易见),如果你计划用它来计算,那么继承使用BigInteger类所带来的性能损失. (7认同)

Pet*_*rey 16

这是一个很快得到大数字的例子.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ZubinMukerjee 但是 BigDecimal 上的 pow 和 sqrt 也不便宜。它比迭代好,但并不像听起来那么简单。 (2认同)

Cli*_*ler 12

结账BigDecimalBigInteger.


Rup*_*rma 5

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));
    }
}
Run Code Online (Sandbox Code Playgroud)