Skip to content

Commit 2c87e51

Browse files
author
n.bitounis
committed
Changed implementation to use BigInteger and simple factorials with a twist of caching.
1 parent 5bdecfd commit 2c87e51

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed
Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,31 @@
1-
using System;
1+
using System.Collections.Generic;
2+
using System.Numerics;
23

34
namespace Algorithms.Numeric
45
{
56
public static class BinomialCoefficients
67
{
8+
private static readonly Dictionary<uint, BigInteger> Cache = new Dictionary<uint, BigInteger>();
9+
710
/// <summary>
811
/// Calculate binomial coefficients, C(n, k).
912
/// </summary>
10-
public static ulong Calculate(uint n, uint k)
13+
public static BigInteger Calculate(uint n)
1114
{
12-
ulong result = 1;
13-
14-
// Since C(n, k) = C(n, n-k)
15-
if (k > n - k)
16-
k = n - k;
15+
return Factorial(2 * n) / (Factorial(n) * Factorial(n + 1));
16+
}
1717

18-
// Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1]
19-
for (int i = 0; i < k; ++i)
18+
private static BigInteger Factorial(uint n)
19+
{
20+
if (n <= 1)
21+
return 1;
22+
if (Cache.ContainsKey(n))
2023
{
21-
result *= Convert.ToUInt64(n - i);
22-
result /= Convert.ToUInt64(i + 1);
24+
return Cache[n];
2325
}
24-
25-
return result;
26+
var value = n * Factorial(n - 1);
27+
Cache[n] = value;
28+
return value;
2629
}
27-
2830
}
29-
30-
}
31+
}

0 commit comments

Comments
 (0)