* Exact binomial coefficient for bigint n, k. * * - k < 0 → 0 (no combinatorial meaning, regardless of n). * - n ≥ 0 and k > n → 0 (standard convention). * - n < 0 → the standard extension via Pascal's rule analytic continuation: * Binomial(n, k) = (-1)^k · Binomial(k-n-1, k), e.g. * Binom
( n: bigint, k: bigint, deadline?: number )
| 63 | if (!Number.isFinite(n) || n < 0) return Infinity; |
| 64 | if (n < 3) return 1; |
| 65 | const lnN = Math.log(n); |
| 66 | const lnB = n * lnN - n * Math.log(lnN) - n; |
| 67 | return lnB > 0 ? lnB / Math.LN10 : 1; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Exact binomial coefficient for bigint n, k. |
| 72 | * |
| 73 | * - k < 0 → 0 (no combinatorial meaning, regardless of n). |
| 74 | * - n ≥ 0 and k > n → 0 (standard convention). |
| 75 | * - n < 0 → the standard extension via Pascal's rule analytic continuation: |
| 76 | * Binomial(n, k) = (-1)^k · Binomial(k-n-1, k), e.g. |
| 77 | * Binomial(-2, 3) = (-1)³·Binomial(4, 3) = -4 (matches Mathematica/sympy). |
| 78 | * |
| 79 | * Returns `undefined` (stay symbolic) rather than an exact bigint when the |
| 80 | * result would exceed MAX_EXACT_COMBINATORICS_DIGITS decimal digits — e.g. |
| 81 | * `Binomial(2e9, 1e9)` has ~6×10⁸ digits, pathological to build. |
| 82 | */ |
| 83 | function binomialBigint( |
| 84 | n: bigint, |
| 85 | k: bigint, |
| 86 | deadline?: number |
| 87 | ): bigint | undefined { |
| 88 | if (k < 0n) return 0n; |
| 89 | if (n < 0n) { |
| 90 | const sign = k % 2n === 0n ? 1n : -1n; |
| 91 | const inner = binomialBigint(k - n - 1n, k, deadline); |
| 92 | return inner === undefined ? undefined : sign * inner; |
no test coverage detected