据我了解,双方java.lang.Long并java.math.BigInteger可以容纳非常大的自然数.
我也知道Long的最大值,但BigInteger的最大值是多少?
除了容量之外,BigInteger在处理仍然落在Long范围内的一般大整数时会表现得更好吗?
唯一的考虑因素是:我的价值对于龙来说太大了吗?
如何提高Java的Big Integer的性能?
例如,这个阶乘程序:
import java.math.*;
class Fac {
public static void main(String[] args) {
BigInteger i = BigInteger.ONE;
for(BigInteger z=BigInteger.valueOf(2);z.compareTo(BigInteger.valueOf(99999)) != 0;) {
i = i.multiply(z);
z = z.add(BigInteger.ONE);
}
System.out.println( i );
}
}
Run Code Online (Sandbox Code Playgroud)
该计划在31.5s 完成
C++中的位置:
#include <iostream>
#include <gmpxx.h>
using namespace std;
int main() {
mpz_class r;
r = 1;
for(int z=2;z<99999;++z) {
r *= mpz_class(z);
}
cout << r << endl;
}
Run Code Online (Sandbox Code Playgroud)
在1.0s 完成
和Ruby(用于比较):
puts (2...99999).inject(:*)
Run Code Online (Sandbox Code Playgroud)
在4.4s(Ruby)和32.2JRuby中完成 …