为什么计算realtively小数字阶乘(34+)返回0 [英] Why computing factorial of realtively small numbers (34+) returns 0

查看:242
本文介绍了为什么计算realtively小数字阶乘(34+)返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;

for (int i = 1; i <= n; i++)
{
    factorial *= i;    
}
Console.WriteLine(factorial);

这code在控制台应用程序运行,但是当一个数字是34以上的应用程序返回0。

This code runs in Console Application, but when a number is above 34 application returns 0.

为什么返回0,并可以做些什么来计算大数阶乘?

Why 0 is returned and what can be done to compute factorial of large numbers?

推荐答案

您打算出什么样的变量可以存储范围。这实际上是一个因子,生长比指数更快。尝试使用 ULONG (最大值2 ^ 64 = 18,446,744,073,709,551,615),而不是INT(最大值2 ^ 31 = 2,147,483,647) - ULONG p = 1 - 这应该让你远一点。

You're going out of range of what the variable can store. That's effectively a factorial, which grows faster than the exponential. Try using ulong (max value 2^64 = 18,446,744,073,709,551,615) instead of int (max value 2^31 = 2,147,483,647) - ulong p = 1 - that should get you a bit further.

如果你需要更进一步,.NET 4及以上有<一个href=\"http://msdn.microsoft.com/en-us/library/system.numerics.biginteger%28v=vs.100%29.aspx\"><$c$c>BigInteger,它可以存储任意大量涌现。

If you need to go even further, .NET 4 and up has BigInteger, which can store arbitrarily large numbers.

这篇关于为什么计算realtively小数字阶乘(34+)返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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