So my task is: I have the number 100, and I have to print the sum of the digits of it's factorial.
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.
My code:
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();
}
}
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:
- use floating point numbers. Asuming you can live with their inherent inprecision and all the other Floating point stuff.
- 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.
Personally I tend to squeeze operations into the BigInt rather then use Floating point numbers. But that is a personal mater.
I've been playing around with my own large math research projects. You can use the .NET BigInteger class (under System.Numerics), but it's not the most efficient library out there.
If you aren't stuck on .NET, I'd suggest using the GNU Multiple Precision Arithmetic Library (https://gmplib.org/). It is both far faster and has far more functionality. You will need to study the docs to learn to use it properly.
Ports of it do exist, though I haven't seen a great port from an API perspective - do a search on Nuget.
来源:https://stackoverflow.com/questions/52933554/im-using-ulong-for-the-factorial-of-100-but-it-still-overflows