hdu 1042 大数阶乘(优化)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1042

hdu坑了,这题不优化过不了

//一个长度较短的数乘与一个大数的乘法 

//TLE了,刘汝佳的算法也需要优化,因为即使超过了f的位数,循环仍在进行,而算法没有求f的位数 
//f=f*i之后位数增加,超出的位数实际上是容易知道的
 
#include<cstdio> 
#include<string.h>
using namespace std;

const int maxn=50000;
int n;
int f[maxn];

int main (){
    
    while(scanf("%d",&n)!=EOF){
        memset(f,0,sizeof(f));
        f[0]=1;
        int len=1;
        for(int i=2;i<=n;i++)
        {
            int j,c=0;
            for(j=0;j<len;j++)
            {
                int tmp=f[j]*i+c;
                c=tmp/10;
                f[j]=tmp%10;
            }
            //超出的数是c,我们就可以把c按位数拆分,赋值给后面的f,每赋值一次位数加1 
            while(c!=0)
            {
                f[j]=c%10;
                c/=10;
                len++;
                j++;
            }
        }
        int j;
        for(j=maxn-1;j>=0;j--)
            if(f[j])
                break;         
        for(;j>=0;j--)
            printf("%d",f[j]);
        printf("
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/neverchanje/p/3573960.html