HDOJ1042

来源:互联网 发布:淘宝客服月工作计划 编辑:程序博客网 时间:2024/05/21 17:25

题目:

Problem Description
Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!
 

Input
One N in one line, process to the end of file.
 

Output
For each N, output N! in one line.
 

Sample Input
123
 

Sample Output
126
分析:大数阶乘问题,解决方案就是数组存储的思想,题目中的N的范围是0-10000,如果是10000的阶乘,大概是40000位,这么下来肯定是TLE,所以可以考虑用数组一次存储5位来进行优化,那么40000/5=8000来存储就可以了

代码如下:

/**
*@author:StormMaybin
*@Date:2016-05-03
*@Filename:HDOJ1042.c
*/
# include <stdio.h>
# define MAX 8000
int main (void)
{
    int i, j, k, t, N;
    int f[MAX];
    while (scanf ("%d",&N) == 1)
    {
        //每次使用前要清零
        memset (f, 0, sizeof (f));
        f[0] = 1;
        for (i = 2; i <= N; i++)
        {
            for (t = 0, j = 0; j < MAX; j++)
            {
                k = f[j] * i + t;
                f[j] = k % 100000;
                t = k / 100000;
            }
        }
        //除去前导零
        for (i = MAX - 1; ! f[i]; i--);
        //第一个元素不要求输出多余零
        printf ("%d",f[i]);
        while (i)
        {
            printf ("%05d",f[--i]);
            //这些需要输出前面多余的零,这个你懂的,否则一直WA!
        }
        printf ("\n");
    }
    return 0;
}


0 0