本题要求实现一个打印非负整数阶乘的函数。
函数接口定义:
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)
{
unsigned long long n1 = N, num = 1;
int Num[3001] = { 0 };
int i, j, k = 1; //k 现有位数
int n = 0; //控制进位
if (n1 < 0 || n1 > 1000)
{
printf("Invalid input\n");
return;
}
if (n1 < 21)
{
while (n1 > 0)
{
num *= n1;
n1--;
}
printf("%llu\n", num);
}
else
{
Num[0] = 1;
for (i = 2; i <= N; ++i)
{
for (j = 0; j < k; ++j)
{
int t = Num[j] * i + n; // 和每位相乘+进位
Num[j] = t % 10;
n = t / 10;
}
while (n) //判断进位
{
Num[k] = n % 10;
k++;
n /= 10;
}
}
for (i = k - 1; i >= 0; --i)
{
printf("%d", Num[i]);
}
printf("\n");
}
}