Skip to content

feat: added binomial coefficient function and the corresponding test #10 #141

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
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
24 changes: 24 additions & 0 deletions maths/binomial_coefficient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Factorial } from "./factorial";
/**
* @function BinomialCoefficient
* @description Calculate the binomial coefficient (n choose k) of two input numbers.
* @param {number} n - the total number of items
* @param {number} k - the number of items to be chosen
* @return {number} - Binomial coefficient (n choose k)
* @see https://en.wikipedia.org/wiki/Binomial_coefficient
* @example BinomialCoefficient(5, 2) = 10
* @example BinomialCoefficient(10, 3) = 120
* @example BinomialCoefficient(6, 0) = 1
*/

export const BinomialCoefficient = (n: number, k: number): number => {
// Check if k is larger than n or negative
if (k > n || k < 0) {
return 0;
}

// Calculate the binomial coefficient using the implemented factorial
const numerator = Factorial(n);
const denominator = Factorial(k) * Factorial(n - k);
return numerator / denominator;
};
34 changes: 34 additions & 0 deletions maths/test/binomial_coefficient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { BinomialCoefficient } from '../binomial_coefficient';

describe('BinomialCoefficient', () => {
it('should calculate the correct binomial coefficient', () => {
// Test cases with expected results
const testCases: [number, number, number][] = [
[5, 2, 10],
[10, 3, 120],
[6, 0, 1],
[4, 4, 1],
[7, 5, 21],
[10, 10, 1],
];

// Iterate through each test case and verify the result
testCases.forEach(([n, k, expected]) => {
const result = BinomialCoefficient(n, k);
expect(result).toEqual(expected);
});
});

it('should return 0 if k is larger than n or negative', () => {
const invalidCases: [number, number][] = [
[5, 6], // k is larger than n
[10, -3], // k is negative
[5, 10], // k is larger than n
];

invalidCases.forEach(([n, k]) => {
const result = BinomialCoefficient(n, k);
expect(result).toEqual(0);
});
});
});