ACM:大数问题

5 篇文章 0 订阅

大数问题参考

									## I Love Big Numbers !

A Japanese young girl went to a Science Fair at Tokyo. There she met with a Robot named Mico-12,
which had AI (You must know about AI-Artificial Intelligence). The Japanese girl thought, she can
do some fun with that Robot. She asked her, “Do you have any idea about maths?”. “Yes! I love
mathematics”, The Robot replied.
“Okey! Then I am giving you a number, you have to find out the Factorial of that number. Then
find the sum of the digits of your result!. Suppose the number is 5. You first calculate 5! = 120, then
find sum of the digits 1 + 2 + 0 = 3. Can you do it?”.
“Yes. I can do!” Robot replied.
“Suppose the number is 100, what will be the result?”. At this point the Robot started thinking
and calculating. After a few minutes the Robot head burned out and it cried out loudly “Time Limit
Exceeds”.
The girl laughed at the Robot and said “The sum is definitely 648”.
“How can you tell that?” Robot asked the girl. “Because I am an ACM World Finalist and I can
solve the Big Number problems easily”.
Saying this, the girl closed her laptop computer and went away.
Now, your task is to help the Robot with the similar problem.
Input
The input file will contain one or more test cases.
Each test case consists of one line containing an integers n (n ≤ 1000).
Output
For each test case, print one line containing the required number. This number will always fit into an
integer, i.e. it will be less than 231 − 1.
Sample Input
5
60
100
Sample Output
3
288
648

#include <bits/stdc++.h>
using namespace std;
const int N = 1000;
const int L = 3000;
int a[N+1][L],digits[N+1];
void init()
{
    memset(a,0,sizeof(a));
    int len = 1;
    a[1][0] = 1;
    for(int i = 2;i <= N;i++)
    {
        int carry = 0;
        for(int j = 0; j < len;j++)
        {
            int t = a[i-1][j]*i + carry;
            carry = t / 10;
            a[i][j] = t % 10;
        }
        while(carry)
        {
            a[i][len++] = carry % 10;
            carry /= 10;
        }
        digits[i] = len;
    }
}
int main()
{
    init();
    int n;
    while(~scanf("%d",&n))
    {
        int ans = 0;
        for(int i = 0;i <= digits[n];i++)
        {
            ans += a[n][i];
        }
        printf("%d\n",ans);
    }
    return 0;
}

二维数组a[][],第一维意义是 i 的阶乘,a[1][]即使指1的阶乘的值

此题计算阶乘,本质上是大数的乘法,在外嵌套一个for循环即可

第二维代表的是每一位,while中的语句意思是将carry逐位送入高位,由于 j 到 len 就截止了,所以len++表示高位进位加1。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值