日期:2014-05-20  浏览次数:20910 次

【300分】如何算99999的阶乘?
刚刚测试了一下System.Numerics.BigInteger类,最简单的阶乘...结果吓了我一跳...

先来月经的递归算法...
C# code
static System.Numerics.BigInteger Factorial(System.Numerics.BigInteger i)
{
    if (i.IsZero || i.Sign == -1)
        return System.Numerics.BigInteger.Zero;
    if (i.IsOne)
        return System.Numerics.BigInteger.One;
    else
        return i * Factorial(i - 1);
} 

static void Main(string[] args)
{
    if (args.Length < 1)
        return; 

    int i;
    if (int.TryParse(args[0], out i))
    {
        System.Numerics.BigInteger bi = i;
        System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
        bi = Factorial(bi);
        sw.Stop();
        //计算结果太长,只输出结果长度
        Console.Write("结果长度:{0} 用时:{1}", bi.ToString().Length, sw.Elapsed);
    }
}

Release运行...

9999! 结果长度:35656 用时:00:00:02.6131329
15000! 结果长度:56130 用时:00:00:08.6232216
15102! 结果长度:56556 用时:00:00:08.8157251 

不幸由于递归堆栈溢出的问题,我测试的运行环境(x86)最大只能算到15102,15103即堆栈溢出...

于是优化一下,改为循环算法...
C# code
static System.Numerics.BigInteger Factorial(System.Numerics.BigInteger i)
{
    System.Numerics.BigInteger result = 1;
    while (true)
    {
        if (i < 2)
            return result;

        result *= i;
        i--;
    }
}


9999! 结果长度:35656 用时:00:00:00.2164311
15000! 结果长度:56130 用时:00:00:00.5164868
15102! 结果长度:56556 用时:00:00:00.5154113

效率很惊人,但还没完...

99999! 结果长度:456569 用时:00:00:36.1188483

36秒多!看来微软在匆匆推出System.Numerics又匆匆撤回后做了大量的优化...

那么999999能算吗?答案是能!结果是多少?抱歉,我这儿还没算完,跑了10多分钟了...

值得一提的是这段代码运行时内存占有并不大,很稳定...工作设置内存在11MB左右,专用工作集内存在5MB左右...即使是现在正在计算999999!,也不过12MB左右和6MB左右...

还要注意一点...System.Numerics并没有包含在C#项目的默认引用中,需要添加引用程序集...这是为什么呢?因为F#!但是...明天上午我有事要早睡,以后有空再介绍吧...

------解决方案--------------------
接分啊啊啊啊啊
------解决方案--------------------
。。。 就多看了两眼
------解决方案--------------------
MARK
------解决方案--------------------
你这个沙发板凳不留的作风不太好
------解决方案--------------------
比我写的那个快多了:http://topic.csdn.net/u/20100318/14/9d47ec28-6b69-4c3f-98ea-c8e53157c779.html
------解决方案--------------------
。。。
------解决方案--------------------
可以安装一个 VS2010 试试.
------解决方案--------------------
那样就可以啊 是不
------解决方案--------------------
沙发地板都被人占了!我就来占过位置!
------解决方案--------------------
你这个沙发板凳不留的作风不太好批评的同时进行膜拜
------解决方案--------------------
说实话对于System.Numerics.BigInteger的效率挺失望的,其乘法运算肯定没有使用FFT,否则绝对不会这么慢,我试了一下算999999,大概得10分钟左右(还不包括输出),而用开源项目IntX,计算部分只需要30多秒,差距太大了,4.0的System.Numerics.BigInteger大数乘法的效率其实还不如3.5下用反射弄出来的那个快。

附IntX的网址

http://intx.codeplex.com/releases/view/41807

C# code

using System;
using System.Collections.Generic;
using System.Linq;
using Oyster.Math;

namespace csdnTest
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime beginTime = DateTime.Now;
            IntX result = Factorial(1000000);
            DateTime endTime = DateTime.Now;
            Console.WriteLine(endTime - beginTime);
            Console.WriteLine(result);
            Console.ReadKey();
        }

        static IntX Factorial(int n)
        {
            int[] counter = GetPowCounter(n);
            SortedDictionary<IntX, bool> sDict = new SortedDictionary<IntX, bool>();

            //计算幂乘并将结果压入优先队列(使用优化过的大数乘法,在计算相等规模的大数乘法时,效率最高)
            for (int i = 2; i <= n; i++)
            {
                if (counter[i] > 0)
                    sDict.Add(IntX.Pow(i, (uint)counter[i]), false);
            }

            IntX valueA = 1, valueB;
            
            //用SortedDictionary模拟优先队列进行最后的计算
            while (sDict.Count > 1)
            {
                valueA = sDict.ElementAt(0).Key;
                valueB = sDict.ElementAt(1).Key;
                sDict.Remove(valueA);
                sDict.Remove(valueB);
                sDict.Add(valueA * valueB, false);
            }

            return sDict.ElementAt(0).Key;
        }

        //做质因数分解,以便使用幂乘进行计算
        static int[] GetPowCounter(int n)
        {
            int[] pList = GetPrime(n);
            int[] pCounter = new int[n + 1];

            for (int i = 0; i < pList.Length; i++)
            {
                int k = n;
                while ((k /= pList[i]) > 0)
                    pCounter[pList[i]] += k;
            }

            return pCounter;
        }

        //生成质数列表
        static int[] GetPrime(int n)
        {
            List<int> prime = new List<int>();
            bool[] flags = new bool[n + 1];

            for (int i = 2; i <= n; i++)
            {
                if (!flags[i])
                    prime.Add(i);

                for (int j = 0; j < prime.Count; j++)
                {
                    if (prime[j] * i > n) break;
                    flags[prime[j] * i] = true;
                    if (i % prime[j] == 0) break;
                }
            }

            return prime.ToArray();
        }
    }
}