要求:
实现一个打印非负整数阶乘的函数
N是用户传入的参数,其值不超过1000。如果N是非负整数,则该函数必须在一行中打印出N!的值,否则打印“Invalid input”
1 #include <stdio.h>
2
3 void Print_Factorial( const int N);
4 int main(){
5 int N;
6 scanf("%d",&N);
7 Print_Factorial(N);
8 return 0;
9 }
10 void Print_Factorial( const int N){
11 if(N<0){
12 puts("Invalid input");
13 return;
14 }
15
16 int num[3001]={0};
17 int k,n;
18 k=1; //位数
19 n=0; //进位
20 num[0]=1;
21 int tmp;
22
23 //将临时结果的每位与阶乘元素相乘
24 for(int i=2;i<=N;i++){
25 for(int j=0;j<k;j++){
26 tmp=num[j]*i+n;
27 num[j]=tmp%10;
28 n=tmp/10;
29 }
30 while(n){
31 num[k++]=n%10;
32 n/=10;
33 }
34 }
35 for(int i=k-1;i>=0;i--){
36 printf("%d",num[i]);
37 }
38 puts("");
39 }
- int范围为10^9,long long int范围为10^18
- 采用斯特林公式,当N=12时,计算结果已经为9位,N=1000时结果将超过long long int范围
- 采用模拟乘法计算阶乘
参考:
https://blog.csdn.net/weixin_42584977/article/details/90771118
来源:https://www.cnblogs.com/cxc1357/p/12222823.html