博客园 首页 私信博主 显示目录 隐藏目录 管理 动画

N的阶乘 51Nod - 1057(10000以内的阶乘)


#include <iostream>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <string.h>

using namespace std;
void jc(int n)
{
    int a[50000],i,j,k,ce,te,m;
    m=1;
    memset(a,0,sizeof(a));
    a[1]=1;
    for(i=2; i<=n; i++)
    {
        te=0;
        for(j=1; j<=m; j++)
            a[j]*=i;
        for(j=1; j<=m; j++)
        {
            ce=te+a[j];
            a[j]=ce%10000;
            te=ce/10000;
        }
        while(te)
        {
            m++;
            a[m]=te%10000;
            te/=10000;
        }
    }
    for(i=m; i>=1; i--)
    {
        if(i==m)
            printf("%d",a[i]);
        else
            printf("%04d",a[i]);
    }
    printf("\n");
}

int main()
{
    int n;
    scanf("%d",&n);
        jc(n);
    return 0;
}

 

思路: 大数的阶乘主要是考虑用数组模拟乘法解决,但是简单的
用数组一个元素代表一个数字,很可能会时间超限(当然
,只是有可能会超限,注意一下输出就行了。有大佬博客
http://www.cnblogs.com/zznu17-091041/p/8407632.html)
,用一个元素代表10000以内的数就节省许多时间.
输入N求N的阶乘的准确值。
Input输入N(1 <= N <= 10000)Output输出N的阶乘Sample Input
5
Sample Output
120
posted @ 2018-02-14 17:33  呦呦哟  Views(484)  Comments(1)    收藏  举报
Live2D