我正在使用ulong的100阶乘,但仍然溢出 [英] I'm using ulong for the factorial of 100, but it still overflows

查看:127
本文介绍了我正在使用ulong的100阶乘,但仍然溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的任务是:我有100,并且必须打印阶乘的数字总和.

So my task is: I have the number 100, and I have to print the sum of the digits of it's factorial.

所以我写了代码,找到了一种很好的数字求和方式,但是我的代码不适用于数字100.我检查了10,它可以正常工作.我想到的第一步是,我必须将类型从int更改为更大的类型.我知道(阶乘)的结果将是一个很大的正数,所以我选择ulong,但仍然不起作用.我在这里检查了Stack Overflow,发现的唯一答案建议使用"BigInteger",但我的Visual Studio似乎不知道,我想知道为什么ulong不起作用.

So I wrote the code, found a nice way of summing the digits but my code doesn't work for the number 100. I checked for 10, and it works perfectly. First step that came to my mind, I have to change the type from int to something bigger. I know the result (of the factorial) will be a huge positive number so I choose ulong, but it still doesn't work. I checked around here on Stack Overflow, and the only answers I found suggested using 'BigInteger' but my Visual Studio doesn't seem to know it, and I would like to know WHY ulong doesn't work.

我的代码:

class Program
{
    static ulong factorial(ulong n) //finds the factorial of x
    {
        ulong fact = n;
        for (ulong i=1; i<n; i++)
        {
            fact = fact * i;
        }
        return fact;
    }//***

    static ulong digitsum(ulong n) // sums the digits of n
    {
        ulong sum = 0;
        while (n != 0)
        {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }//***

    static void Main(string[] args)
    {
        ulong x = 100;

        Console.WriteLine(digitsum(factorial(x)));

        Console.ReadLine();
    }
}

推荐答案

所有整数类型都有限制. unsigned long int增加了上限.但是显然还远远不够.正如其他人在评论中所说,乌龙茶将短缺100个数量级.

All integer types have limits. unsigned long int increased the upper limit. But apparently not nearly far enough. As the others have said in comments, ulong is to short by 100+ orders of magnitude.

对于如此庞大的数字,有两种选择:

For such huge numbers there is two options:

  1. 使用浮点数.假设您可以忍受其固有的不精确性以及所有其他浮点数.
  2. 使用
  1. use floating point numbers. Asuming you can live with their inherent inprecision and all the other Floating point stuff.
  2. Use BigInteger. That one will only run into limits like the max objects size or adresseable RAM. So you should be save up to 2 GiB or so.

我个人倾向于将操作压缩到BigInt中,而不是使用浮点数.但这是个人事务.

Personally I tend to squeeze operations into the BigInt rather then use Floating point numbers. But that is a personal mater.

这篇关于我正在使用ulong的100阶乘,但仍然溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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