G-500! ——动态规划基础题

G-500! ——动态规划基础题

描述:
简单的一个动规问题。只需要求出每个数的阶乘,然后输出就行。
考虑到数位很大,将其开成二维数组形式。
考虑到输入会是多组数据
所以要将1000以内的所有数字的阶乘都放在这个二维数组之中,以方便取出。

In these days you can more and more often happen to see programs which perform some useful calculations
being executed rather then trivial screen savers. Some of them check the system message queue
and in case of finding it empty (for examples somebody is editing a file and stays idle for some time)
execute its own algorithm.
As an examples we can give programs which calculate primary numbers.
One can also imagine a program which calculates a factorial of given numbers. In this case it is not
the time complexity of order O(n) which makes troubles, but the memory requirements. Considering
the fact that 500! gives 1135-digit number. No standard, neither integer nor floating, data type is
applicable here.
Your task is to write a programs which calculates a factorial of a given number.
Input
Any number of lines, each containing value n for which you should provide value of n!
Output
2 lines for each input case. First should contain value n followed by character ‘!’. The second should
contain calculated value n!.
Assumptions:
• Value of a number n which factorial should be calculated of does not exceed 1000 (although 500!
is the name of the problem, 500 is a small limit).
• Mind that visually big number of case 4 is broken after 80 characters, but this is not the case in
the real output file.
Sample Input
10
30
50
100
Sample Output
10!
3628800
30!
265252859812191058636308480000000
50!
30414093201713378043612608166064768844377641568960512000000000000
100!
93326215443944152681699238856266700490715968264381621468592963895217599993229915
608941463976156518286253697920827223758251185210916864000000000000000000000000

int a[1001][len];
// a数组用于存储阶乘数组
//数组的初始化以及阶乘数组的形成
void Init_arr()
{
    int l = 1;
    memset(a,-1,sizeof(a));
    a[1][0] = 1;
    a[0][0] = 1;
	//基础初始化
    for (int i=2; i<1001; i++){
        int tmp = 0, m = 0;//m为除最后一位前几位数
        for (int j=0; j<l; j++){
            tmp = a[i-1][j] * i + m;
            m = tmp / 10;
            a[i][j] = tmp % 10;
        }//前一个数数位直接取过来

        while (m!=0){
            a[i][l] = m % 10;
            m = m / 10;
            l++;
        }//在前一个数的基础上 增加数位
    }
}
//从后向前,数位后大前小
void Print(int n){
    cout << n << "!" << endl;  //n!
    for (int i=len-1; i>=0; i--){
        if (a[n][i] == -1)
            continue;
        else
            cout << a[n][i];
    }
    cout << endl;
}
int main()
{
    int n;
    Init_arr();
//    sum();

    while (~scanf("%d", &n))
        Print(n);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值