For solving project euler problem 20 to find the sum of digits in 100! i am running the following program , it is working for factorial of small numbers but not for 100.which data type should i use or is it necessary to use an array for storing the digits?
int rec(int);
void main()
{
int f=1,i=1,z,s=0,r,n;
while(i<=100)
{
f=f*i;
f=rec(f);
i++;
}
n=f;
while(n!=0)
{
r=n%10;
n=n/10;
s=s+r;
}
printf("\n%d",s);
}
int rec(int t)
{
if(t%10==0)
{
t=t/10;
rec(t);
}
return t;
}
You should look for overflow, print the value after each iteration.
Note that
rec(t);doesn’t do anything as it doesn’t use the returned value… you wantt = rec(t);.intis definitely too short, trylong long… if that’s still overflowing, you need another data structure.. eg: GMP Library.Note: using some “proper” language for the job might give you some insight to the range you have to support… e.g. with python: