diff --git a/Maths/BinomialCoefficient.js b/Maths/BinomialCoefficient.js index 65c52dd15d..ffdf2d9e90 100644 --- a/Maths/BinomialCoefficient.js +++ b/Maths/BinomialCoefficient.js @@ -14,8 +14,6 @@ * @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.') @@ -23,9 +21,19 @@ export const findBinomialCoefficient = (n, k) => { 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) } diff --git a/Maths/test/BinomialCoefficient.test.js b/Maths/test/BinomialCoefficient.test.js index 26960b6ab4..e27b40d0cc 100644 --- a/Maths/test/BinomialCoefficient.test.js +++ b/Maths/test/BinomialCoefficient.test.js @@ -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')