我想知道在 Scala 中,是否有任何方法可以计算二项式系数,从 n 中选择 k,或者从一组 n 元素中选择 k 组合的数量。
似乎对于n=1000and k=35,35!即使在使用 Long时,我们在 Scala 中计算时也可能面临溢出问题。
谢谢!
在处理不适合 Int/Long/Float/Double 的数字时使用BigInt和BigDecimal。
def permutations(n: Int): BigInt =
(1 to n).map(BigInt(_)).foldLeft(BigInt(1))(_ * _)
def combinations(n: Int, k: Int): BigInt =
permutations(n) / (permutations(k) * permutations(n - k))
combinations(1000, 35)
// res23: BigInt = 53007599712421378893801108296363791932591235151324218238066214600
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |