18 Star 133 Fork 63

编程语言算法集 / C-Sharp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
BinomialCoefficient.cs 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
Gerson Jr 提交于 2023-12-30 10:33 . Switch to file-scoped namespaces (#430)
using System;
using System.Numerics;
namespace Algorithms.Numeric;
/// <summary>
/// The binomial coefficients are the positive integers
/// that occur as coefficients in the binomial theorem.
/// </summary>
public static class BinomialCoefficient
{
/// <summary>
/// Calculates Binomial coefficients for given input.
/// </summary>
/// <param name="num">First number.</param>
/// <param name="k">Second number.</param>
/// <returns>Binimial Coefficients.</returns>
public static BigInteger Calculate(BigInteger num, BigInteger k)
{
if (num < k || k < 0)
{
throw new ArgumentException("num ≥ k ≥ 0");
}
// Tricks to gain performance:
// 1. Because (num over k) equals (num over (num-k)), we can save multiplications and divisions
// by replacing k with the minimum of k and (num - k).
k = BigInteger.Min(k, num - k);
// 2. We can simplify the computation of (num! / (k! * (num - k)!)) to ((num * (num - 1) * ... * (num - k + 1) / (k!))
// and thus save some multiplications and divisions.
var numerator = BigInteger.One;
for (var val = num - k + 1; val <= num; val++)
{
numerator *= val;
}
// 3. Typically multiplication is a lot faster than division, therefore compute the value of k! first (i.e. k - 1 multiplications)
// and then divide the numerator by the denominator (i.e. 1 division); instead of performing k - 1 divisions (1 for each factor in k!).
var denominator = BigInteger.One;
for (var val = k; val > BigInteger.One; val--)
{
denominator *= val;
}
return numerator / denominator;
}
}
C#
1
https://gitee.com/TheAlgorithms/C-Sharp.git
git@gitee.com:TheAlgorithms/C-Sharp.git
TheAlgorithms
C-Sharp
C-Sharp
master

搜索帮助