首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 使用 BigInteger 實現階乘並緩存中間結果的代碼解析

     編輯:程式設計綜合問答

代碼邏輯


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!
}

解析

  • `table` 靜態緩存已計算階乘,**避免重複計算**。
  • `synchronized` 保證多線程安全擴展緩存。
  • 調用 `factorial(5)` → 循環計算 1!~5! 存入 table;再調 `factorial(3)` 直接 `table.get(3)` O(1) 返回。
  • `BigInteger.valueOf(size)` 將 int 轉大整數,`multiply` 大整數乘法。

適用場景

多次查詢不同 n!、n 較大 (超過 long 范圍) 的場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved