File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- using System ;
1+ using System . Collections . Generic ;
2+ using System . Numerics ;
23
34namespace 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+ }
You can’t perform that action at this time.
0 commit comments