static List table = new ArrayList<>();
static { table.add(BigInteger.ONE); } // 0! = 1
public static synchronized BigInteger factorial(int x) {
for (int size = table.size(); size <= x; size++) {
BigInteger last = table.get(size - 1); // (size-1)!
BigInteger next = last.multiply(BigInteger.valueOf(size)); // size!
table.add(next); // 緩存
}
return table.get(x); // 直接返回 x!
}
多次查詢不同 n!、n 較大 (超過 long 范圍) 的場景。