Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions Maths/BinomialCoefficient.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,26 @@
* @returns {number}
*/

import { calcFactorial } from './Factorial'

export const findBinomialCoefficient = (n, k) => {
if (typeof n !== 'number' || typeof k !== 'number') {
throw Error('Type of arguments must be number.')
}
if (n < 0 || k < 0) {
throw Error('Arguments must be greater than zero.')
}
let product = 1
for (let i = n; i > k; i--) {
product *= i
if (k > n) {
return 0
}
// Multiplicative formula in exact integer arithmetic: after step i the
// running value is exactly C(n, i + 1), since C(n, i) * (n - i) is always
// divisible by (i + 1). BigInt keeps every intermediate exact, unlike the
// factorial formula n! / (k! * (n - k)!), whose large intermediates lose
// integer precision in floating point even for small answers
// (e.g. C(25, 2) evaluated to 299.99999999999994).
const steps = Math.min(k, n - k)
let result = 1n
for (let i = 0; i < steps; i++) {
result = (result * BigInt(n - i)) / BigInt(i + 1)
}
return product / calcFactorial(n - k)
return Number(result)
}
18 changes: 18 additions & 0 deletions Maths/test/BinomialCoefficient.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,24 @@ describe('Testing findBinomialCoefficient function', () => {
expect(binomialCoefficient).toBe(10)
})

it('should return exact integers for larger inputs', () => {
expect(findBinomialCoefficient(25, 2)).toBe(300)
expect(findBinomialCoefficient(26, 6)).toBe(230230)
expect(findBinomialCoefficient(30, 13)).toBe(119759850)
expect(findBinomialCoefficient(52, 5)).toBe(2598960)
})

it('should be symmetric in k and n - k', () => {
expect(findBinomialCoefficient(30, 13)).toBe(
findBinomialCoefficient(30, 17)
)
expect(findBinomialCoefficient(40, 5)).toBe(findBinomialCoefficient(40, 35))
})

it('should return 0 when k is greater than n', () => {
expect(findBinomialCoefficient(3, 5)).toBe(0)
})

it('should throw error when supplied arguments other than number', () => {
expect(() => {
findBinomialCoefficient('eight', 'three')
Expand Down
Loading