N!
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 82480 Accepted Submission(s): 24200
Problem Description
Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!
Input
One N in one line, process to the end of file.
Output
For each N, output N! in one line.
Sample Input
1 2 3
Sample Output
1 2 6
如果正常的的话,递归或者迭代
// 递归计算阶乘
int factorial_recursion(int n){
if(n<=0){
return 1;
}else{
return n * factorial_recursion(n-1);
}
}
// 迭代计算阶乘
int factorial_iteration(int n){
int result = 1;
while(n>1){
result *= n;
n--;
}
return result;
}
不过int不超过14就GG了。
所以还是用数组去模拟,用数组模拟了竖式除法,再输出结果
/*************************************************************************
> File Name: N的阶乘.c
> Author: YinJianxiang
> Mail: YinJianxiang123@gmail.com
> Created Time: 2017年06月20日 星期二 21时54分10秒
************************************************************************/
#include<stdio.h>
#include<string.h>
int main(void) {
long long result[10000];
int num;
int i;
int j;
while(scanf("%d",&num) != EOF) {
memset(result,0,sizeof(result));
result[0] = 1;
for(j = 1;j < num;j++) {
for(i = 0;i < 9999;i++) {
result[i] *= j;
for(i = 0;i < 9999;i++) {
if(result[i] >= 10000) {
result[i+1] += result[i] / 10000;
result[i] %= 10000;
}
}
}
}
for(i = 9999;i >= 0;i--) {
if(result[i]) {
break;
}
}
printf("%lld",result[i]);
for(j = i - 1;j >= 0;j--) {
printf("%05lld",result[i]);
}
printf("\n");
}
return 0;
}