62,614
社区成员
发帖
与我相关
我的任务
分享
import java.math.BigInteger;
public class BigFactorial {
public static void main(String args[]) {
long t0, t1;
t0 = System.currentTimeMillis();
BigInteger bi = factorial(99999);
t1 = System.currentTimeMillis();
System.out.println(t1 - t0);
}
public static BigInteger factorial(int n) {
if(n < 2) {
return BigInteger.ONE;
}
int[] oddCount = new int[Integer.numberOfTrailingZeros(Integer.highestOneBit(n))];
int shift = init(oddCount, n);
BigInteger result = BigInteger.ONE;
BigInteger bg = BigInteger.ONE;
BigInteger tmp = BigInteger.ONE;
int max = oddCount[oddCount.length - 1];
int offset = (oddCount[0] + 1) & 1;
int oddStart = 1;
while(oddStart <= max) {
tmp = tmp.multiply(new BigInteger(String.valueOf(2 * oddStart + 1)));
if(oddCount[offset] == oddStart) {
offset++;
bg = bg.multiply(tmp);
tmp = BigInteger.ONE;
result = result.multiply(bg);
}
oddStart++;
}
return result.shiftLeft(shift);
}
private static int init(int[] oddCount, int n) {
int s = n;
int r = 0;
int k = oddCount.length;
while(k > 0) {
s >>= 1;
oddCount[--k] = n - s - 1;
n = s;
r += s;
}
return r;
}
}