It's a test in a website, here is the code
#include <stdio.h>
void Print_Factorial ( const int N );
int main()
{
int N;
scanf("%d",&N);
Print_Factorial(N--);
return 0;
}
/* your code will be put in here*/
#include <math.h>
int getFactLength(int N){
double length = 0;
while(N){
length += log10(N--);
}
return (int)length+1;
}
void printFact(int fact[], int length){
while(length--){
printf("%d",*fact++);
}
}
void initialNums(int nums[], int length, int num){
while(length--){
*nums++ = num;
}
}
void Print_Factorial( const int N ){
if(N < 0){
printf("Invalid input");
return ;
}
int NT = N;
if(NT>=0 && NT<15){
int fact = 1;
while(NT){
fact *= NT--;
}
printf("%d",fact);
return ;
}
int length = getFactLength(N);
int fact[length];
initialNums(fact, length, 0);
fact[length-1] = 1;
int lastNoneZeroIndex = length-1;
while(NT > 1){
int lengthT = length;
int carry = 0;
while(lengthT-- > lastNoneZeroIndex){
int result = NT*fact[lengthT] + carry;
fact[lengthT] = result % 10;
carry = result / 10;
}
while(carry){
fact[--lastNoneZeroIndex] = carry % 10;
carry /= 10;
}
NT--;
}
printFact(fact, length);
}
I use values from 0
to 20
to test it, all of them are right. But when I submit it in that website, a test case always do not pass. I don't know what that case is. But, there are 5 cases, all test cases are between 0 and 1000, and two of them are no more than 15, one of them is negative, one of them use most time to pass, so I think the case that didnt pass is a number that smaller than 1000. That's all I know, I can't imagine that 1000 was passed, but the number smaller than 1000 didn't pass. I don't know what is wrong with my lovely code. I hope you can watch my code, and find some bugs.
There create a overflow in the fact variable, here you use int type for fact variable. For input 13,14, it gives wrong answer.
Solution:
long long int fact = 1;
or,
change the condition- if(NT>=0 && NT<13)