【题目描述】
求10000以内n的阶乘。
【输入】
只有一行输入,整数n(0<=n<=10000)。
【输出】
一行,即n!的值。
【输入样例】
4
【输出样例】
24
10000*10000 用int 可以存储的下,思路和大整数加法类似,边计算边进位,否则最后两个样例会超时
http://ybt.ssoier.cn:8088/problem_show.php?pid=1172
#include <iostream>
using namespace std;
#define coutInt(a,b) cout << "#" << a << "==" << b << endl;
#define coutArr(a,len) for(int i = 1; i <= len; i++) cout << a[i] << " "; cout << endl;
int n;
const int maxn = 1e5 + 11;
int a[maxn];
int main(int argc, char const *argv[]){
cin >> n;
if(n == 0 || n == 1){
cout << 1;
return 0;
}
memset(a,0,sizeof(a));
a[0] = 1; //代表长度
a[1] = 1; //从下表1,开始存储数据
for(int i = 2; i <= n; i++){
int temp = 0;
for(int j = 1; j <= a[0]; j++){
a[j] *= i;
a[j] += temp;
if(a[j] > 9){
temp = a[j]/10;
a[j] = a[j]%10;
if(j == a[0]) a[j+1] = temp;
}else{
temp = 0;
}
}
//处理末尾一位的进位
int k = a[0] + 1;
while(a[k] > 9){
a[k+1] += a[k]/10;
a[k] = a[k]%10;
k++;
}
//处理数组长度
if(a[k] > 0) a[0] = k;
else a[0] = k-1;
//coutArr(a,a[0]);
}
//输出
for(int i = a[0]; i >= 1; i--) cout << a[i];
return 0;
}