[Solved] CodeChef Small factorial Solution


The problem, as M Oehm has pointed out in the comments, is with the data type that you are using for fact. It is too small to store the factorial of numbers like 100, which contain around 157 digits. You need to use an array to store the digits. Here is my approach to the problem (which has has been accepted by the judge).

#include<stdio.h>

int main()
{
   int t,j;
   scanf("%d",&t);
   while(t--)
   {
     int n;
     scanf("%d",&n);
     int a[1000] = {1};
     int m = 0;
     int carry = 0;
     for(int i=1; i<=n; i++)
     {
       for(j=0; j<=m; j++)
       {
         a[j] = (a[j]*i)+carry;
         carry = a[j]/10;
         a[j] = a[j]%10;
       }
       while(carry)
       {
         m++;
         a[m] = carry%10;
         carry/=10;
       }
     }

     for(int i=m; i>=0; i--)
        printf("%d",a[i]);
     printf("\n");
   }
   return 0;
}

Edit: The original code that I had posted was in C++; but since the question has been tagged C, I have edited the above code for C.

Hope this helps!

0

solved CodeChef Small factorial Solution