微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HDOJ 1042 N! 大数阶乘 - 高精度

HDOJ 1042 N! 大数阶乘
原题 : Problem 1042
http://acm.hdu.edu.cn/showproblem.php?pid=1042

题意:计算n!,这里n<= 10000

分析:很明显的一道大数题,就算用long double 也会数据溢出,因为10000!有30000多位数,所以这里开一个40000大的int数组,其做法就是用数组存储每一位数,用数字乘数组,结果保存在数组里,形成一个循环。

这里写图片描述

假如存储位数的数组为num[],每个存储的结果应该是 int 结果 = num[i] * n + 进位数。
把个位数存在num中, 就是 num[i] = 结果 % 10;
而进位数就是, 进位数 = 结果 / 10;

这里提供两种做法。C++ and C#

这里写图片描述

这里写图片描述

PS :
C++这里全部用指针,本人比较喜欢和习惯用指针,反而用数组做不出。汗,(#--).
C# 这里使用了C#4.0中的BigInteger结构,需要引用System.Numerics.

C++实现

#include <iostream>
#include <cstdio>
#define M 40005 
using namespace std;
int main()
{
    int  n = 0;
    while(scanf("%d",&n) != EOF)
    {
        int num[M]={1};
        int *np = num;
        int len = 1;
        if(n == 0 || n == 1)
        {
            cout << "1" << endl;
            continue;
        }
        for(int i=2; i<=n; i++) 
        {
            int k = len;
            np = num;
            while(k--)              // 数字乘于数组的每位数 
                (*np++) *= i; 

            np = num;
            k = 0;
            while(k++ <= len)       // 进位
            {
                if(*np / 10 > 0)
                {
                    *(np+1) += *np / 10;
                    (*np) %= 10;
                    if(np == num + len - 1) //到达最后一位,长度+1;
                    {
                        if(*(np+1) / 10 > 0)//如果最后一位还可以进位,长度+1;
                            len++;
                        len++;
                    }
                }
                np++;
            }
        }

        for(int i=len-1; i>=0; i--)
            printf("%d",num[i]);
        printf("\n");

    }
    return 0;
}

C#实现

using System;
using System.Numerics;

namespace ConsoleApplication2 {
    class Program {
        static void Main(string[] args)
        {
            BigInteger [] num = new BigInteger[10005];
            num[0] = num[1] = BigInteger.Parse("1");
            for (int i = 1; i <= 10000; i++)
                num[i] = num[i - 1] * i;

            while (true)                            
            {
                string str = Console.ReadLine();
                if (str == null) break;
                int x = Convert.ToInt32(str);
                Console.WriteLine(num[x]);
            }
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐