1+ namespace MathFlow . Core . Combinatorics ;
2+ public static class CombinatoricsFunctions
3+ {
4+ /// <summary>
5+ /// Calculates the GCD.
6+ /// </summary>
7+ public static long GCD ( long a , long b )
8+ {
9+ a = Math . Abs ( a ) ;
10+ b = Math . Abs ( b ) ;
11+
12+ while ( b != 0 )
13+ {
14+ var temp = b ;
15+ b = a % b ;
16+ a = temp ;
17+ }
18+
19+ return a ;
20+ }
21+
22+ /// <summary>
23+ /// Calculates the LCM.
24+ /// </summary>
25+ public static long LCM ( long a , long b )
26+ {
27+ return Math . Abs ( a * b ) / GCD ( a , b ) ;
28+ }
29+
30+ /// <summary>
31+ /// Calculates the factorial.
32+ /// </summary>
33+ public static double Factorial ( double n )
34+ {
35+ if ( n < 0 || n != Math . Floor ( n ) )
36+ throw new ArgumentException ( "Factorial is only defined for non-negative integers" ) ;
37+
38+ if ( n > 170 )
39+ return double . PositiveInfinity ;
40+
41+ double result = 1 ;
42+ for ( int i = 2 ; i <= ( int ) n ; i ++ )
43+ result *= i ;
44+
45+ return result ;
46+ }
47+
48+ /// <summary>
49+ /// Calculates the binomial coefficient.
50+ /// </summary>
51+ public static double Binomial ( double n , double k )
52+ {
53+ if ( n < 0 || n != Math . Floor ( n ) || k < 0 || k != Math . Floor ( k ) )
54+ throw new ArgumentException ( "Binomial is only defined for non-negative integers" ) ;
55+
56+ if ( n < 0 || k < 0 || k > n )
57+ return 0 ;
58+
59+ if ( k > n - k )
60+ k = n - k ;
61+
62+ double result = 1 ;
63+ for ( int i = 1 ; i <= k ; i ++ )
64+ {
65+ result *= n - ( k - i ) ;
66+ result /= i ;
67+ }
68+
69+ return result ;
70+ }
71+
72+ /// <summary>
73+ /// Calculates the number of permutations.
74+ /// </summary>
75+ public static double Permutation ( double n , double k )
76+ {
77+ if ( n < 0 || n != Math . Floor ( n ) || k < 0 || k != Math . Floor ( k ) || k > n )
78+ throw new ArgumentException ( "Permutation is only defined for non-negative integers with k <= n" ) ;
79+
80+ double result = 1 ;
81+ for ( int i = 0 ; i < k ; i ++ )
82+ result *= n - i ;
83+
84+ return result ;
85+ }
86+ }
0 commit comments