Skip to content

Commit f0122e4

Browse files
feat: add iterative factorial algorithm
1 parent 5c39e87 commit f0122e4

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

‎Maths/FactorialIterative.js‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @function factorialIterative
3+
* @description Calculates the factorial of a non-negative integer
4+
* using an iterative approach. The factorial of n (n!) is the
5+
* product of all positive integers less than or equal to n.
6+
* @param {number} n - A non-negative integer
7+
* @returns {number} - The factorial of n
8+
* @see https://en.wikipedia.org/wiki/Factorial
9+
* @example factorialIterative(0) => 1
10+
* @example factorialIterative(5) => 120
11+
* @example factorialIterative(10) => 3628800
12+
*/
13+
const factorialIterative = (n) => {
14+
if (!Number.isInteger(n) || n < 0) {
15+
throw new TypeError('Input must be a non-negative integer')
16+
}
17+
let result = 1
18+
for (let i = 2; i <= n; i++) {
19+
result *= i
20+
}
21+
return result
22+
}
23+
24+
export { factorialIterative }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { factorialIterative } from '../FactorialIterative.js'
2+
3+
describe('factorialIterative', () => {
4+
test('factorialIterative(0) returns 1', () => {
5+
expect(factorialIterative(0)).toBe(1)
6+
})
7+
8+
test('factorialIterative(1) returns 1', () => {
9+
expect(factorialIterative(1)).toBe(1)
10+
})
11+
12+
test('factorialIterative(2) returns 2', () => {
13+
expect(factorialIterative(2)).toBe(2)
14+
})
15+
16+
test('factorialIterative(3) returns 6', () => {
17+
expect(factorialIterative(3)).toBe(6)
18+
})
19+
20+
test('factorialIterative(5) returns 120', () => {
21+
expect(factorialIterative(5)).toBe(120)
22+
})
23+
24+
test('factorialIterative(7) returns 5040', () => {
25+
expect(factorialIterative(7)).toBe(5040)
26+
})
27+
28+
test('factorialIterative(10) returns 3628800', () => {
29+
expect(factorialIterative(10)).toBe(3628800)
30+
})
31+
32+
test('factorialIterative(12) returns 479001600', () => {
33+
expect(factorialIterative(12)).toBe(479001600)
34+
})
35+
36+
test('throws TypeError for negative input', () => {
37+
expect(() => factorialIterative(-1)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float input', () => {
41+
expect(() => factorialIterative(1.5)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for string input', () => {
45+
expect(() => factorialIterative('5')).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)