C 一个计算大数阶乘的程序

C 一个计算大数阶乘的程序,c,factorial,C,Factorial,这是一个网站测试,下面是代码 #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 getFactLengt

这是一个网站测试,下面是代码

#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);
}
#包括
无效打印因子(常量整数N);
int main()
{
int N;
scanf(“%d”和“&N”);
列印因子(N-);
返回0;
}
/*您的代码将放在这里*/
#包括
int getFactLength(int N){
双倍长度=0;
while(N){
长度+=log10(N-);
}
返回(int)长度+1;
}
无效打印事实(整数事实[],整数长度){
while(长度--){
printf(“%d”,*fact++);
}
}
void initialNums(int nums[],int length,int num){
while(长度--){
*nums++=num;
}
}
无效打印因数(常数整数N){
if(N<0){
printf(“无效输入”);
返回;
}
int NT=N;
如果(NT>=0&&NT 1){
int lengthT=长度;
整数进位=0;
while(长度-->lastNoneZeroIndex){
int结果=NT*事实[长度]+进位;
事实[长度]=结果%10;
进位=结果/10;
}
while(携带){
事实[--lastNoneZeroIndex]=进位%10;
进位/=10;
}
新台币--;
}
打印事实(事实、长度);
}

我使用
0
20
的值来测试它,它们都是正确的。但当我在那个网站上提交时,测试用例总是不通过。我不知道那是什么案子。但是,有5个案例,所有的测试案例都在0到1000之间,其中两个不超过15个,一个是阴性的,其中一个用了最多的时间通过,所以我认为没有通过的案例是一个小于1000的数字。这就是我所知道的,我无法想象1000通过了,但是小于1000的数字没有通过。我不知道我可爱的代码出了什么问题。我希望您可以查看我的代码,并找到一些bug。

在事实变量中创建了一个溢出,这里您使用int-type作为事实变量。 对于输入13,14,它给出了错误的答案

解决方案:

long int事实=1

或者


更改条件-
if(NT>=0&&NT也尝试在大输入上测试您的程序。例如,您是否检查过,如果输入为100,您的程序是否返回933262155443941526816992388562667004907159682664381621468599296389521759993229915690941463976765182862536979220827223758251185210916864000000000000000000?您的程序实际上计算了1000!我相信是正确的您的格式有问题。您没有在阶乘后打印新行。可能自动查克会这样做。(新行也会刷新输出。)这个问题要求输出必须在一行中,但当数字太长时,它会旋转,如何确保输出在一行中?我测试了100,是的。我找不到比这更大的阶乘数。非常感谢!你是对的。12!大于4亿,13!将溢出。