目录
本题要求实现一个打印非负整数阶乘的函数。
函数接口定义:
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
代码实现:
#include<stdio.h>
void Print_Factorial(const int N)
{
if (N < 0)
printf("Invalid input");
else
{
int arr[3000] = { 0 };
int i = 0;
int arrlength = 1;
int rest = 0;
arr[0] = 1;
for (i = 1; i <= N; i++)
{
int j = 0;
for (j = 0; j < arrlength; j++)
{
int tmp = i * arr[j] + rest;
arr[j] = tmp % 10;
rest = tmp / 10;
}
while (rest)
{
arr[arrlength++] = rest % 10;
rest /= 10;
}
}
for (i = arrlength - 1; i >= 0; i--)
{
printf("%d", arr[i]);
}
}
}