给定 n,要求计算 n!,直接用C/C++标准类型int/long long存不下,想要用数组,数组的一个单元表示阶乘结果的一位。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int ans[10005];
int main()
{
int n;
cin >> n;
if(n == 0)
cout << "0";
else {
ans[1]=1;
int up=0,temp,len=1; // up为进位 len为当前结果的长度
for(int i=2;i<=n;i++) {
for(int l=1;l<=len;l++) {
temp = ans[l]*i+up;
ans[l] = temp%10; //留下的数
up = temp/10; // 下一轮的进位
}
while(up != 0) { // 当位数增加,需要继续进位的时候
ans[++len] = up%10;
up /= 10; //这句好像用不到吧?进位好像不会大于10吧??
}
}
for(int l=len;l>=1;l--)
cout << ans[l];
cout << endl;
}
}