For the problem Small Factorials I wrote the following C Code. It is working on my PC. I cross-checked the answer for 100! with a Python Script so answer is correct. I don't have any idea why this is giving wrong answer.
I am using an integer array to store the digits. 4 digits at each array index. Lowest 4 digits at ans[0], next 4 at ans1 and so on.
What's wrong here?
#include<stdio.h>
#define LIMIT 10000
#define ANS_SIZE 40
int main()
{
int tests, num, ans[ANS_SIZE];
register short int i, j, k;
long temp;
scanf("%d", &tests);
for(k = 1; k <= tests; k++)
{
scanf("%d", &num);
ans[0] = 1;
for(i = 1; i < ANS_SIZE; i++)
ans[i] = 0;
for(i = 2; i <= num; i++)
{
ans[ANS_SIZE - 1] *= i;
for(j = ANS_SIZE - 2 ; j >= 0 ; j--)
{
temp = ans[j] * i;
ans[j] = temp % LIMIT;
ans[j + 1] += temp/LIMIT;
}
}
for(i = (ANS_SIZE - 1); i >= 0; i--)
if(ans[i] != 0)
break;
printf("%d", ans[i]);
i--;
for(; i >= 0; i--)
{
if(ans[i] > 999)
printf("%d", ans[i]);
else if(ans[i] > 99)
printf("0%d", ans[i]);
else if(ans[i] > 9)
printf("00%d", ans[i]);
else if(ans[i] > 0)
printf("000%d", ans[i]);
else
printf("0000");
}
printf("\n");
}
return 0;
}