本题要求实现一个打印非负整数阶乘的函数。
函数接口定义:
void Print_Factorial ( const int N );
其中N是用户传入的参数,其值不超过1000。如果N是非负整数,则该函数必须在一行中打印出N!的值,否则打印“Invalid input”。
裁判测试程序样例:
#include <stdio.h>
void Print_Factorial ( const int N );
int main()
{
int N;
scanf("%d", &N);
Print_Factorial(N);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
15
输出样例:
1307674368000
void Print_Factorial ( const int N) {
int num[3000] = {0};
num[0] = 1;
int n = 0, k = 1; // n 为进的数,k 为当前结果的总位数
for (int i=2; i<=N; i++) {
for (int j=0; j<k; j++) {
int temp = i * num[j] + n;//每一位相乘 再+进位
num[j] = temp % 10;//更新每一位的数字
n = temp / 10; //判断能否进位
if (n && j==k-1) {
k++;
} // 当有进位且已经处理到最前位时才开拓目标数组的下一位
}
}
for (int i=k-1; i>=0; i--) {
if (N >= 0) {
printf("%d", num[i]);
} else {
printf("Invalid input");
}
}
printf("\n");
}