-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathbinomialcoefficient.go
More file actions
35 lines (31 loc) · 855 Bytes
/
binomialcoefficient.go
File metadata and controls
35 lines (31 loc) · 855 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
34
35
// binomialcoefficient.go
// description: Returns C(n, k)
// details:
// a binomial coefficient C(n,k) gives number ways
// in which k objects can be chosen from n objects.
// wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient
// time complexity: O(k) or O(n-k) whichever is smaller (O(n) in worst case)
// space complexity: O(1)
// author: Akshay Dubey (https://github.com/itsAkshayDubey)
// see binomialcoefficient_test.go
package math
import (
"errors"
)
var ErrPosArgsOnly error = errors.New("arguments must be positive")
// C is Binomial Coefficient function
// This function returns C(n, k) for given n and k
func Combinations(n int, k int) (int, error) {
if n < 0 || k < 0 {
return -1, ErrPosArgsOnly
}
if k > (n - k) {
k = n - k
}
res := 1
for i := 0; i < k; i++ {
res *= (n - i)
res /= (i + 1)
}
return res, nil
}