题目来自杭电:http://acm.hdu.edu.cn/showproblem.php?pid=1042
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
代码:
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
int n;
int i;
int j;
int digit; //总位数
int a[40000];
int carry; //进位
int temp;
int len;
//ofstream cout("out.txt");
while(cin >> n){
memset(a,0,sizeof(a));
temp = 0;
digit = 1;
a[0] = 1;
for(i = 2;i <= n;i++){
carry = 0;
for(j = 1;j <= digit;j++){
temp = a[j-1] * i + carry;
a[j-1] = temp % 10;
carry = temp /10;
}
while(carry){
a[++digit - 1] = carry % 10;
carry /= 10;
}
}
for(i = digit-1;i >= 0;i--)
cout << a[i];
cout << endl;
}
return 0;
}
总结:还是大数问题,一般情况下12的阶乘就已经溢出,因此考虑用数组存储,关于大数阶乘,有很多很多好的算法,此处只是个很简单的,仅仅比递归想的多了点,奉上大神之作http://blog.youkuaiyun.com/whdugh/article/details/9364245