Skip to content
Open
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
29 changes: 29 additions & 0 deletions Maths/PrimeFactorization.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @function primeFactorization
* @description Returns all prime factors of a given positive integer.
* Prime factorization is the process of determining which prime numbers
* multiply together to make the original number.
* @param {number} n - A positive integer greater than 1
* @returns {number[]} - An array of prime factors in ascending order
* @see https://en.wikipedia.org/wiki/Integer_factorization
* @example primeFactorization(12) => [2, 2, 3]
* @example primeFactorization(28) => [2, 2, 7]
* @example primeFactorization(13) => [13]
*/
const primeFactorization = (n) => {
if (!Number.isInteger(n) || n < 2) {
throw new TypeError('Input must be an integer greater than or equal to 2')
}
const factors = []
let num = n
for (let i = 2; i <= Math.sqrt(num); i++) {
while (num % i === 0) {
factors.push(i)
num = Math.floor(num / i)
}
}
if (num > 1) factors.push(num)
return factors
}

export { primeFactorization }
43 changes: 43 additions & 0 deletions Maths/test/PrimeFactorization.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { primeFactorization } from '../PrimeFactorization.js'

describe('primeFactorization', () => {
test('primeFactorization(2) returns [2]', () => {
expect(primeFactorization(2)).toEqual([2])
})

test('primeFactorization(12) returns [2, 2, 3]', () => {
expect(primeFactorization(12)).toEqual([2, 2, 3])
})

test('primeFactorization(28) returns [2, 2, 7]', () => {
expect(primeFactorization(28)).toEqual([2, 2, 7])
})

test('primeFactorization(13) returns [13]', () => {
expect(primeFactorization(13)).toEqual([13])
})

test('primeFactorization(100) returns [2, 2, 5, 5]', () => {
expect(primeFactorization(100)).toEqual([2, 2, 5, 5])
})

test('primeFactorization(360) returns [2, 2, 2, 3, 3, 5]', () => {
expect(primeFactorization(360)).toEqual([2, 2, 2, 3, 3, 5])
})

test('primeFactorization of a prime returns that prime', () => {
expect(primeFactorization(97)).toEqual([97])
})

test('throws TypeError for 1', () => {
expect(() => primeFactorization(1)).toThrow(TypeError)
})

test('throws TypeError for negative input', () => {
expect(() => primeFactorization(-12)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => primeFactorization(12.5)).toThrow(TypeError)
})
})
Loading