Binomial coefficient implementation (#1094)

This commit is contained in:
Akshay Dubey
2022-09-08 10:14:33 +05:30
committed by GitHub
parent 6c718c01d4
commit 644d7f7faa
2 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,31 @@
/*
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
* Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient
* function to find binomial coefficient of numbers n and k.
* return binomial coefficient of n,k
*/
/**
* @function findBinomialCoefficient
* @description -> this function returns bonimial coefficient
* of two numbers n & k given by n!/((n-k)!k!)
* @param {number} n
* @param {number} k
* @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
}
return product / calcFactorial(n - k)
}

View File

@ -0,0 +1,29 @@
import { findBinomialCoefficient } from '../BinomialCoefficient.js'
describe('Testing findBinomialCoefficient function', () => {
it('should return 56', () => {
const binomialCoefficient = findBinomialCoefficient(8, 3)
expect(binomialCoefficient).toBe(56)
})
it('should return 10', () => {
const binomialCoefficient = findBinomialCoefficient(5, 2)
expect(binomialCoefficient).toBe(10)
})
it('should throw error when supplied arguments other than number', () => {
expect(() => { findBinomialCoefficient('eight', 'three') }).toThrow(Error)
})
it('should throw error when n is less than zero', () => {
expect(() => { findBinomialCoefficient(-1, 3) }).toThrow(Error)
})
it('should throw error when k is less than zero', () => {
expect(() => { findBinomialCoefficient(1, -3) }).toThrow(Error)
})
it('should throw error when n and k are less than zero', () => {
expect(() => { findBinomialCoefficient(-1, -3) }).toThrow(Error)
})
})