Skip to content

Commit 644d7f7

Browse files
Binomial coefficient implementation (#1094)
1 parent 6c718c0 commit 644d7f7

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

Maths/BinomialCoefficient.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
3+
* Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient
4+
* function to find binomial coefficient of numbers n and k.
5+
* return binomial coefficient of n,k
6+
*/
7+
8+
/**
9+
* @function findBinomialCoefficient
10+
* @description -> this function returns bonimial coefficient
11+
* of two numbers n & k given by n!/((n-k)!k!)
12+
* @param {number} n
13+
* @param {number} k
14+
* @returns {number}
15+
*/
16+
17+
import { calcFactorial } from './Factorial'
18+
19+
export const findBinomialCoefficient = (n, k) => {
20+
if ((typeof n !== 'number') || (typeof k !== 'number')) {
21+
throw Error('Type of arguments must be number.')
22+
}
23+
if (n < 0 || k < 0) {
24+
throw Error('Arguments must be greater than zero.')
25+
}
26+
let product = 1
27+
for (let i = n; i > k; i--) {
28+
product *= i
29+
}
30+
return product / calcFactorial(n - k)
31+
}
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { findBinomialCoefficient } from '../BinomialCoefficient.js'
2+
3+
describe('Testing findBinomialCoefficient function', () => {
4+
it('should return 56', () => {
5+
const binomialCoefficient = findBinomialCoefficient(8, 3)
6+
expect(binomialCoefficient).toBe(56)
7+
})
8+
9+
it('should return 10', () => {
10+
const binomialCoefficient = findBinomialCoefficient(5, 2)
11+
expect(binomialCoefficient).toBe(10)
12+
})
13+
14+
it('should throw error when supplied arguments other than number', () => {
15+
expect(() => { findBinomialCoefficient('eight', 'three') }).toThrow(Error)
16+
})
17+
18+
it('should throw error when n is less than zero', () => {
19+
expect(() => { findBinomialCoefficient(-1, 3) }).toThrow(Error)
20+
})
21+
22+
it('should throw error when k is less than zero', () => {
23+
expect(() => { findBinomialCoefficient(1, -3) }).toThrow(Error)
24+
})
25+
26+
it('should throw error when n and k are less than zero', () => {
27+
expect(() => { findBinomialCoefficient(-1, -3) }).toThrow(Error)
28+
})
29+
})

0 commit comments

Comments
 (0)