-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathBinomialCoefficients.cs
More file actions
33 lines (30 loc) · 892 Bytes
/
BinomialCoefficients.cs
File metadata and controls
33 lines (30 loc) · 892 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System.Collections.Generic;
using System.Numerics;
namespace Algorithms.Numeric
{
public static class BinomialCoefficients
{
private static readonly Dictionary<uint, BigInteger> Cache = new Dictionary<uint, BigInteger>();
/// <summary>
/// Calculate binomial coefficients, C(n, k).
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
public static BigInteger Calculate(uint n)
{
return Factorial(2 * n) / (Factorial(n) * Factorial(n + 1));
}
private static BigInteger Factorial(uint n)
{
if (n <= 1)
return 1;
if (Cache.ContainsKey(n))
{
return Cache[n];
}
var value = n * Factorial(n - 1);
Cache[n] = value;
return value;
}
}
}