Skip to content

Commit 88a6ed7

Browse files
feat: add prime factorization algorithm
1 parent 5c39e87 commit 88a6ed7

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎Maths/PrimeFactorization.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @function primeFactorization
3+
* @description Returns all prime factors of a given positive integer.
4+
* Prime factorization is the process of determining which prime numbers
5+
* multiply together to make the original number.
6+
* @param {number} n - A positive integer greater than 1
7+
* @returns {number[]} - An array of prime factors in ascending order
8+
* @see https://en.wikipedia.org/wiki/Integer_factorization
9+
* @example primeFactorization(12) => [2, 2, 3]
10+
* @example primeFactorization(28) => [2, 2, 7]
11+
* @example primeFactorization(13) => [13]
12+
*/
13+
const primeFactorization = (n) => {
14+
if (!Number.isInteger(n) || n < 2) {
15+
throw new TypeError('Input must be an integer greater than or equal to 2')
16+
}
17+
const factors = []
18+
let num = n
19+
for (let i = 2; i <= Math.sqrt(num); i++) {
20+
while (num % i === 0) {
21+
factors.push(i)
22+
num = Math.floor(num / i)
23+
}
24+
}
25+
if (num > 1) factors.push(num)
26+
return factors
27+
}
28+
29+
export { primeFactorization }
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { primeFactorization } from '../PrimeFactorization.js'
2+
3+
describe('primeFactorization', () => {
4+
test('primeFactorization(2) returns [2]', () => {
5+
expect(primeFactorization(2)).toEqual([2])
6+
})
7+
8+
test('primeFactorization(12) returns [2, 2, 3]', () => {
9+
expect(primeFactorization(12)).toEqual([2, 2, 3])
10+
})
11+
12+
test('primeFactorization(28) returns [2, 2, 7]', () => {
13+
expect(primeFactorization(28)).toEqual([2, 2, 7])
14+
})
15+
16+
test('primeFactorization(13) returns [13]', () => {
17+
expect(primeFactorization(13)).toEqual([13])
18+
})
19+
20+
test('primeFactorization(100) returns [2, 2, 5, 5]', () => {
21+
expect(primeFactorization(100)).toEqual([2, 2, 5, 5])
22+
})
23+
24+
test('primeFactorization(360) returns [2, 2, 2, 3, 3, 5]', () => {
25+
expect(primeFactorization(360)).toEqual([2, 2, 2, 3, 3, 5])
26+
})
27+
28+
test('primeFactorization of a prime returns that prime', () => {
29+
expect(primeFactorization(97)).toEqual([97])
30+
})
31+
32+
test('throws TypeError for 1', () => {
33+
expect(() => primeFactorization(1)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for negative input', () => {
37+
expect(() => primeFactorization(-12)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float input', () => {
41+
expect(() => primeFactorization(12.5)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)