【清华机试】N!(0<=N<=1000)

来源:互联网 发布:淘宝如何办理退货 编辑:程序博客网 时间:2024/05/18 00:47
#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int maxn = 3002;     // 1000 的阶乘约 2600 位int a[maxn] = {0};         // 存储 N 的阶乘char num[1002][maxn] = {0}; // 存储每一个 N!int main(){    int i = 2;      // 遍历2-n    int j = 1;    int len = 1;    // 数组长度,默认为1    int count = 0;  // 计数器    // 求解 1!~1000!, 空间换时间    a[1] = 1;    for(i = 2; i <= 1000; ++i)    {        // 每一位乘以i        for(j = 1; j <= len; ++j)        {            a[j] *= i;        }        // 移位        for(j = 1; j <= len; ++j)        {            if(a[j] > 9)            {                a[j+1] += a[j]/10;                a[j] %= 10;                // 处理高位进位                if(len == j)                {                    len++;                }            }        }        // 不用过滤前面的0, len就指向的最高位        count = 0;        for(j = len; j >= 1; --j)        {            num[i][count++] = '0'+a[j];        }        num[i][count] = '\0';   // 存储结尾的'\0'    }    int n;    while(cin >> n)    {        if(n == 0)        {            // 0!            cout << "1" << endl;        }        else        {            printf("%s\n", num[n]);        }    }    return 0;}
1 0
原创粉丝点击