高精度阶乘(递归版)

来源:互联网 发布:带windows系统的平板 编辑:程序博客网 时间:2024/05/21 15:47

高精度阶乘

这是递归版的高精度阶乘

#include<iostream>#include<cstring>using namespace std;int a[5000000000];int sum = 0,n,len = 1;void e(){    int c = 0,j;    sum++;    for(int i = 1;i<=len;i++)    {        a[i] = sum*a[i] + c;        c = a[i]/10;         a[i]%=10;    }    j = len+1;        while(c)        {            a[j] = c%10;            j++;                c/=10;        }        j--;    len = j;    if(sum == n)    {        for(int i = len;i>=1;i--)        cout<<a[i];        return;    }    e();}int main(){    cin>>n;    for(int i = 0;i<200;i++)    {        a[i] = 0;    }    a[1] = 1;    e();    return 0;}

这个计算高精度没有问题,就是时间复杂度很高,望高手帮忙指出指出问题o(~ ̄︶ ̄~)o,优化优化


下面这个时间复杂度更高,不过没用递归(递归也是循环吧),一样的,不过这个有用优点


#include<iostream>using namespace std;int r[10000000],a[1000000],b[1000000],t[1000000];int main(){    int n,j = 1,len;    cin>>n;    a[1] = 1;    for(int i = 1;i<=n;i++)    {        int temp = i,w = 1;        while(temp>0)        {            t[w++] = temp%10;            temp /= 10;        }        w--;        for(int z = w,v = 1;z>=1;z--,v++)        {            b[v] = t[z];        }        for(int o = 1;o<=j;o++)        {            int add = 0;            for(int p = 1,e = w;p<=w;p++,e--)            {                r[o+p-1] += a[o]*b[e] + add;                add = r[o+p-1]/10;                r[o+p-1] %= 10;            }            r[o+w] = add;        }        len = j+w;        while(!r[len] && len>1)        {            len--;        }        for(int u = 1;u<=len;u++)        {            a[u] = r[u];            r[u] = 0;        }        j = len;    }    for(int i = len;i>=1;i--)    {        cout<<a[i];    }    return 0;}

没有注释,不好的习惯,就这样吧

原创粉丝点击