[英]A program that calculate the factorial of big number
这是在网站上的测试,这是代码
#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);
}
我用0
到20
值来测试它,它们都是正确的。 但是当我在那个网站提交它时,一个测试用例总是不通过。 我不知道那是什么情况。 但是,有5个案例,所有测试案例都在0到1000之间,其中两个不超过15个,其中一个是负数,其中一个使用最多的时间通过,所以我认为没有通过的案例是一个小于1000的数字。我知道的就这些,我无法想象1000通过了,但小于1000的数字没有通过。 我不知道我可爱的代码有什么问题。 我希望你能看我的代码,并找出一些错误。
在事实变量中创建了一个溢出,这里你使用 int 类型作为事实变量。 对于输入 13,14,它给出了错误的答案。
解决方案:
long long int fact = 1;
或者,
改变条件- if(NT>=0 && NT<13)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.