UVa10220:I Love Big Numbers !
题目大意
给定正整数n,求n!的各位数字之和。
例:给定n为5,5!=120,答案是1+2+0=3
Solution
简单粗暴,直接求出n!然后计算各位数字之和。因为n最大可能为1000,所以需要采用高精度计算,具体实现方式与Uva623一致,可以参考我的另一篇博客。
AC-Code(C++)
Time:0ms
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <climits>
#include <ctime>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const int maxn = 1000 + 10;
int number[maxn][maxn];
int len[maxn];
int getAns(int x){
int ans = 0;
for(int i=0;i<len[x];i++){
int temp = number[x][i];
while(temp > 0){
ans += temp % 10;
temp /= 10;
}
}
return ans;
}
int main(int argc, const char * argv[]) {
// freopen("input.txt", "r", stdin);
int n;
number[0][0] = 1;
len[0] = 1;
for(int i=1;i<=1000;i++){
memcpy(&number[i][0], &number[i-1][0], len[i-1] * sizeof(int));
len[i] = len[i-1];
int carry = 0;
for(int j=0;j<len[i-1];j++){
number[i][j] *= i;
number[i][j] += carry;
carry = number[i][j] / 10000; // stored 4 digit in each unit of number
number[i][j] %= 10000;
}
if(carry > 0)
number[i][len[i]++] = carry;
}
while(scanf("%d",&n)==1){
printf("%d\\n",getAns(n));
}
return 0;
}