From 414e374ab40b148365d733017305f0aca28701aa Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Mon, 28 Dec 2020 13:11:01 +0200 Subject: [PATCH] Add primeFactors --- snippets/primeFactors.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 snippets/primeFactors.md diff --git a/snippets/primeFactors.md b/snippets/primeFactors.md new file mode 100644 index 000000000..959db4d85 --- /dev/null +++ b/snippets/primeFactors.md @@ -0,0 +1,29 @@ +--- +title: primeFactors +tags: math,algorithm,beginner +--- + +Finds the prime factors of a given number using the trial division algorithm. + +- Use a `while` loop to iterate over all possible prime factors, starting with `2`. +- If the current factor, `f`, exactly divides `n`, add `f` to the factors array and divide `n` by `f`. Otherwise, increment `f` by one. + +```js +const primeFactors = n => { + let a = [], + f = 2; + while (n > 1) { + if (n % f === 0) { + a.push(f); + n /= f; + } else { + f++; + } + } + return a; +}; +``` + +```js +primeFactors(147); // [3, 7, 7] +```