C#,阶乘(Factorials)的递归、非递归、斯特林近似及高效算法与源代码

Christian Kramp
阶乘是基斯顿·卡曼(Christian Kramp,1760~1826)于 1808 年发明的运算符号,是数学术语。
一个正整数的阶乘(factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。
亦即n!=1×2×3×...×(n-1)×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n。
在多项式、插值等等很多的额计算机算法中都需要阶乘的计算。

本文发布的算法包括:
(1)非递归方法
(2)递归方式
(3)斯特林近似方法


(4)阶乘的C#高效实现
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;namespace Legalsoft.Truffer.Algorithm
{public static partial class Algorithm_Gallery{public static long Factorial_While(int n){long res = 1;while (n > 1){res *= n;n = n - 1;}return res;}public static long Factorial_Recurse(int n){if (n == 1){return 1;}else{return n * Factorial_Recurse(n - 1);}}public static long Factorial_Stirling_Approximation(int n){if (n <= 1){return 1;}double z = System.Math.Sqrt(2 * Math.PI * n) * System.Math.Pow((n / Math.E), n);return (long)(z);}public static string Factorial_Longlong(int n){if (n < 0){return "n必须为正整数";}if (n == 0 || n == 1){return "1";}const int MaxLength = Int32.MaxValue / 8;int[] array = new int[MaxLength];array[0] = 1;int valid = 1;for (int i = 2; i <= n; i++){int carry = 0;for (int j = 0; j < valid; j++){int multipleResult = (array[j] * i) + carry;array[j] = multipleResult % 10;carry = multipleResult / 10;}if (carry != 0){array[valid++] = (carry % 10);}}int[] result = new int[valid];Array.Copy(array, result, valid);return String.Join("", result.ToArray().Reverse());}}
}
一直以来,由于阶乘定义的不科学,导致以后的阶乘拓展以后存在一些理解上得困扰,和数理逻辑的不顺。
阶乘从正整数一直拓展到复数。传统的定义不明朗。所以必须科学再定义它的概念
真正严谨的阶乘定义应该为:对于数n,所有绝对值小于或等于n的同余数之积。称之为n的阶乘,即n!
对于复数应该是指所有模n小于或等于│n│的同余数之积。。。对于任意实数n的规范表达式为:
正数 n=m+x,m为其正数部,x为其小数部
负数n=-m-x,-m为其正数部,-x为其小数部
对于纯复数
n=(m+x)i,或n=-(m+x)i
我们再拓展阶乘到纯复数:
正实数阶乘: n!=│n│!=n(n-1)(n-2)....(1+x).x!=(i^4m).│n│!
负实数阶乘: (-n)!=cos(m )│n│!=(i^2m)..n(n-1)(n-2)....(1+x).x!
(ni)!=(i^m)│n│!=(i^m)..n(n-1)(n-2)....(1+x).x!
(-ni)!=(i^3m)│n│!=(i^3m)..n(n-1)(n-2)....(1+x).x!
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
