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:
Personally I tend to squeeze operations into the BigInt rather then use Floating point numbers. But that is a personal mater.