diff --git a/maths/prime_factorization.ts b/maths/prime_factorization.ts new file mode 100644 index 00000000..19032730 --- /dev/null +++ b/maths/prime_factorization.ts @@ -0,0 +1,27 @@ +/** + * @description Get exponenets of each prime number in factorization of a number n + * @param {number} n - A natural number. + * @return {Map} - factorization of number n. + * @see https://en.wikipedia.org/wiki/Integer_factorization + * @example factorize(4) = Map {2 => 2} + * @example factorize(5) = Map {5 => 1} + */ +export const factorize = (n: number): Map => { + let result: Map = new Map(); + + for (let i = 2; i * i <= n; i++) { + while (n % i == 0) { + let occurence = result.get(i); + if (!occurence) occurence = 0; + result.set(i, occurence + 1); + n = n / i; + } + } + if (n > 1) { + let occurence = result.get(n); + if (!occurence) occurence = 0; + result.set(n, occurence + 1); + } + + return result; +}; diff --git a/maths/test/prime_factorization.test.ts b/maths/test/prime_factorization.test.ts new file mode 100644 index 00000000..23eaff0b --- /dev/null +++ b/maths/test/prime_factorization.test.ts @@ -0,0 +1,26 @@ +import { factorize } from "../prime_factorization"; + + +interface TestCase { + n: number; + expected: Map +} + +const cases: TestCase[] = [ + {n: 4, expected: new Map([[2, 2]])}, + {n: 5, expected: new Map([[5, 1]])}, + {n: 7, expected: new Map([[7, 1]])}, + {n: 10, expected: new Map([[2, 1], [5, 1]])}, + {n: 999, expected: new Map([[3, 3], [37, 1]])}, + {n: 999999999999878, expected: new Map([[2, 1], [19, 1], [26315789473681, 1]])}, +]; + +describe("factorize", () => { + + test.each(cases)( + "prime factorization of $n should be $expected", + ({n, expected}) => { + expect(factorize(n)).toEqual(expected); + }, + ); +});