大数价乘算法。

来源:互联网 发布:淘宝购买记录查询软件 编辑:程序博客网 时间:2024/04/28 16:25

阶乘函数(n!),随着n的增大,函数结果的增长速度很快,很容易就溢出了。下面我们自己定义一个大数阶乘函数。
其实原理很简单,就是我们小学时学过的乘法算式的原理。将结果存在一个数组里,数组的每一个元素为结果的一个十进位。用第一个大于0,小于等于n的自然数去重每一位。需要进位时,要注意进位。

这种方法不仅可以应用在阶乘方面,还可以应用于其它的大数运算过程当中。

   1:  static uint[] Factorial(uint n) 
   2:  {
   3:      uint[] array = new uint[10000];
   4:      array[0] = 1;
   5:   
   6:      uint carry = 0;
   7:      uint digit = 1;
   8:      uint container;
   9:   
  10:      for (uint i = 2; i <= n; i++) {
  11:          carry = 0;
  12:          for (uint j = 0; j < digit; j++) {
  13:              container = array[j] * i + carry;
  14:              array[j] = container % 10;//当前位
  15:              carry = container / 10;//进位值
  16:          }
  17:          //更高位
  18:          if (carry != 0) {
  19:              array[digit++] = carry % 10;
  20:          }
  21:      }
  22:   
  23:      uint[] result = new uint[digit];
  24:   
  25:      Array.Copy(array, result, digit);
  26:   
  27:      return result;
  28:  }
.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }