Java中的大数

Java中的大数

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

我试过了long但是这个最大值为9223372036854775807,当使用一个整数时,它没有保存足够的数字,因此不足以满足我的需要。

这附近有吗?


MMMHUHU
浏览 372回答 3
3回答

婷婷同学_

您可以使用BigInteger整数和BigDecimal对于带有十进制数的数字。两个类都是在java.math包裹。例子:BigInteger reallyBig = new BigInteger("1234567890123456890");BigInteger notSoBig = new BigInteger("2743561234"); reallyBig = reallyBig.add(notSoBig);

拉莫斯之舞

这里有一个例子,它很快就得到了大量的数字。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;     }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java