diff --git a/Maths/FactorialIterative.js b/Maths/FactorialIterative.js new file mode 100644 index 0000000000..21159c3d26 --- /dev/null +++ b/Maths/FactorialIterative.js @@ -0,0 +1,24 @@ +/** + * @function factorialIterative + * @description Calculates the factorial of a non-negative integer + * using an iterative approach. The factorial of n (n!) is the + * product of all positive integers less than or equal to n. + * @param {number} n - A non-negative integer + * @returns {number} - The factorial of n + * @see https://en.wikipedia.org/wiki/Factorial + * @example factorialIterative(0) => 1 + * @example factorialIterative(5) => 120 + * @example factorialIterative(10) => 3628800 + */ +const factorialIterative = (n) => { + if (!Number.isInteger(n) || n < 0) { + throw new TypeError('Input must be a non-negative integer') + } + let result = 1 + for (let i = 2; i <= n; i++) { + result *= i + } + return result +} + +export { factorialIterative } diff --git a/Maths/test/FactorialIterative.test.js b/Maths/test/FactorialIterative.test.js new file mode 100644 index 0000000000..51b3c8d23f --- /dev/null +++ b/Maths/test/FactorialIterative.test.js @@ -0,0 +1,47 @@ +import { factorialIterative } from '../FactorialIterative.js' + +describe('factorialIterative', () => { + test('factorialIterative(0) returns 1', () => { + expect(factorialIterative(0)).toBe(1) + }) + + test('factorialIterative(1) returns 1', () => { + expect(factorialIterative(1)).toBe(1) + }) + + test('factorialIterative(2) returns 2', () => { + expect(factorialIterative(2)).toBe(2) + }) + + test('factorialIterative(3) returns 6', () => { + expect(factorialIterative(3)).toBe(6) + }) + + test('factorialIterative(5) returns 120', () => { + expect(factorialIterative(5)).toBe(120) + }) + + test('factorialIterative(7) returns 5040', () => { + expect(factorialIterative(7)).toBe(5040) + }) + + test('factorialIterative(10) returns 3628800', () => { + expect(factorialIterative(10)).toBe(3628800) + }) + + test('factorialIterative(12) returns 479001600', () => { + expect(factorialIterative(12)).toBe(479001600) + }) + + test('throws TypeError for negative input', () => { + expect(() => factorialIterative(-1)).toThrow(TypeError) + }) + + test('throws TypeError for float input', () => { + expect(() => factorialIterative(1.5)).toThrow(TypeError) + }) + + test('throws TypeError for string input', () => { + expect(() => factorialIterative('5')).toThrow(TypeError) + }) +})