#include<stdio.h>
long int f(int);
int main()
{
int t,n;
scanf("%d",&t);
if(t>=0 && t<=100)
while(t)
{scanf("%d",&n);
if(n>=0 && n<=100)
printf("%ld\n",f(n));
else return 0;
t–;
}
return 0;
}
long int f(int n)
{ if (n==1 || n == 0)
return 1;
else
return n*f(n-1);
}
The problem is that you are using long int to store the result while the answer in this case may be very huge since the factorial function grows very fast. No data type in C/C++ will be sufficient to store the result. You will need to store the result in an array.
Please refer to this awesome tutorial by @kuruma to see how this can be done.
Also you do not need to explicitly check for input constraints like if(t>=0 && t<=100) as they are ensured by the problem setter when generating test cases.You can go to the coding part straight away!
1 Like