对于大输入返回负数的阶乘函数

2024-03-10

我的阶乘函数似乎适用于 1 到 6 之间的数字,但不适用于大于 6 的数字,例如从 21 开始!结果是否定的。

我不明白为什么。这是我的功能:

factorial :: Int -> Int
factorial 0 = 1
factorial 1 = 1
factorial num = num * factorial( num - 1)

这是我的二项式系数函数,它调用我的阶乘函数(也许问题来自于此?):

binomialCoef :: Int -> Int -> Int
binomialCoef n 1 = n
binomialCoef n k = factorial n `div` 
                        ((factorial k) * factorial (n - k))

(…) 意识到我的阶乘函数返回从 21 开始的负数!,我不明白为什么。

Because an Int has a fixed number of bits. An Int should at least represent all numbers between -2-29 and 229-1, and on a 64-bit system, typically it will represent numbers between -2-63 and 263-1, but regardless what bounds it represents, it will eventually run out of bits to represent such number.

您可以与Integer https://hackage.haskell.org/package/base-4.14.1.0/docs/Prelude.html#t:Integer表示任意大数:

factorial :: Integer -> Integer
factorial 0 = 1
factorial 1 = 1
factorial num = num * factorial (num-1)

例如:

Prelude> factorial 21
51090942171709440000
Prelude> factorial 22
1124000727777607680000
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对于大输入返回负数的阶乘函数 的相关文章

随机推荐