File tree Expand file tree Collapse file tree 1 file changed +17
-16
lines changed Expand file tree Collapse file tree 1 file changed +17
-16
lines changed Original file line number Diff line number Diff line change 1
- using System ;
1
+ using System . Collections . Generic ;
2
+ using System . Numerics ;
2
3
3
4
namespace Algorithms . Numeric
4
5
{
5
6
public static class BinomialCoefficients
6
7
{
8
+ private static readonly Dictionary < uint , BigInteger > Cache = new Dictionary < uint , BigInteger > ( ) ;
9
+
7
10
/// <summary>
8
11
/// Calculate binomial coefficients, C(n, k).
9
12
/// </summary>
10
- public static ulong Calculate ( uint n , uint k )
13
+ public static BigInteger Calculate ( uint n )
11
14
{
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
+ }
17
17
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 ) )
20
23
{
21
- result *= Convert . ToUInt64 ( n - i ) ;
22
- result /= Convert . ToUInt64 ( i + 1 ) ;
24
+ return Cache [ n ] ;
23
25
}
24
-
25
- return result ;
26
+ var value = n * Factorial ( n - 1 ) ;
27
+ Cache [ n ] = value ;
28
+ return value ;
26
29
}
27
-
28
30
}
29
-
30
- }
31
+ }
You can’t perform that action at this time.
0 commit comments