我似乎无法在 .Net 中找到任何内置的阶乘函数,我觉得这很奇怪。 在许多语言中,例如 python,标准库中有阶乘函数...
我不想每次都需要自己的阶乘函数 在解决方案中。
我宁愿不从 Nuget 获取一些库只是为了得到一个 阶乘函数,这很愚蠢...
我希望在 F# 和 C# 中使用阶乘函数。
Google 搜索淹没了想要编写或展示如何编写您自己的阶乘函数的人。
我是否忽略了阶乘函数,或者在 System.Math、System.Numerics 或其他任何地方真的没有内置阶乘函数? (如果任何标准库,那么在任何标准库中都没有这个功能的动机是什么?)
是的,我知道它写起来很简单,并且可以像这样定义
let rec factorial = function
| x when x = 0 -> 1
| x -> x*factorial(x-1)
但我不想每次都需要这个函数时都写那个,而且仅仅为了这种简单的函数而创建自己的库也感觉很傻......
最佳答案
您可以 utilise the BigInteger
class为此
但是,如果您对使用原始类型的高性能解决方案感兴趣,这应该可以解决问题:
private static readonly int[] factorial = new int[]{
1,
1,
2,
6,
24,
120,
720,
5040,
40320,
362880,
3628800,
39916800,
479001600,
1932053504,
};
public static int Factorial(int x) {
if(x < 0) {
throw new ArithmeticException("negative faculty");
}
if(x >= faculty.Length) {
throw new OverflowException();
}
return faculty[x];
}
关于c# - 标准库阶乘函数.Net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622428/