大输入的阶乘函数返回负数 [英] Factorial function returning negative number for large input

查看:54
本文介绍了大输入的阶乘函数返回负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的阶乘函数似乎适用于1到6之间的数字,但不适用于比6大得多的数字,例如以21开头!结果是否定的.

My factorial function seems to work for numbers between 1 and 6, but not for numbers much bigger than 6, for example starting with 21! the results are negative.

我不知道为什么.这是我的功能:

I cannot figure out why. Here's my function:

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

这是我的二项式系数函数,它调用了我的阶乘函数(也许问题出在这个函数上?):

And here's my binomial coefficient function that calls my factorial function (maybe the problem comes from this one ?):

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

推荐答案

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

(…) realized my factorial function returns negative numbers starting at 21!, and I can't figure out why.

因为 Int 具有固定的位数. Int 至少应表示-2 -29 和2 29 -1之间的所有数字,在64位系统上,通常将表示介于-2 -63 和2 63 -1之间的数字,但是无论其表示什么边界,它最终都将用完表示该数字的位.

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.

您可以使用 整数 代表任意大数字:

You can work with Integer to represent arbitrary large numbers:

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

例如:

Prelude> factorial 21
51090942171709440000
Prelude> factorial 22
1124000727777607680000

这篇关于大输入的阶乘函数返回负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆