我们如何在C#中计算千位数的阶乘? [英] How can we calculate factorial of thousand of number in C#?

查看:78
本文介绍了我们如何在C#中计算千位数的阶乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi
我们如何计算C中千位数的阶乘?



i使用此代码但如果我输入2000则没有找到结果。

请帮帮我。



代码:



hi How can we calculate factorial of thousand of number in C#

i use this code but if i input 2000 then no result is found.
please help me.

code:

long x = Convert.ToInt32(TextBox1.Text);
long fact = 1;
if (x == 1)
 {
    Label1.Visible = true;
    Label1.Text = Convert.ToString(fact);
 }
 else
  {
    long i = 1;
    while (i <= x)
    {
        fact = fact * i;
        i++;
    }
    Label1.Visible = true;
    Label1.Text = Convert.ToString(fact);
   }

推荐答案

查找BigInteger类。这可能需要一段时间,但它会得到一个确切的答案。我相信它内置于.NET 4中。
Look up the BigInteger class. It might take a while, but it will get an exact answer. I believe it is built into .NET 4.


你一定是在开玩笑!我只是计算了阶乘,它由整数值表示,其十进制表示长度为77388位小数!



没有CPU整数类型可以携带这么多信息。



如果您可以使用Framework 4.0,您可以使用 System.Numerics.BigInteger 进行此类计算:



You must be joking! I just calculated that factorial, it is expressed by the integer value with its decimal presentation which is 77388 decimal places long!

No CPU integer type can carry so much information.

If you can use Framework 4.0 you can use System.Numerics.BigInteger for such calculation:

static BigInteger Factorial(int arg) {
    BigInteger value = 1;
    for (int index = 2; index <= arg; index++)
        value *= index;
    return value;
}





让我们测试它并与最大 long 进行比较:





Let's test it and compare with maximum long:

string factorial = string.Format("{0} decimal places", Factorial(20000)); 
Console.WriteLine(factorial.Length);
Console.WriteLine(long.MaxValue);





输出:



Output:

77338 decimal places
9223372036854775807





对不起我不喜欢我想打印长度为77338的整数值。

难怪你不能用 long 来做到这一点!



-SA


令人惊叹的问题。我从没想过这个,但这是真的。实际上,double是.NET中最大的数据类型,但2000的阶乘将是如此巨大的价值,计算机实际上无法保持这个价值。



这就是为什么即使我使用双数据类型运行您的代码,值2000的答案是无限。



请尝试下面的代码并查看:)



Mind blowing question. I never thought this out but this is true. Actually double is the largest data type in .NET but the factorial of 2000 will be such a huge value that computer is actually not able to hold the value.

Thats why even if I run your code with double data type, the answer that comes for value 2000 is Infinity.

Try my code below and see :)

long x = Convert.ToInt32(2000);
double fact = 1;
if (x == 1)
{
}
else
{
    long i = 1;
    while (i <= x)
    {
        fact = fact * i;
        i++;
    }
    MessageBox.Show(Convert.ToString(fact));
}


这篇关于我们如何在C#中计算千位数的阶乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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