Get the prime factors of a given number

in code

This solution uses the Sieve of Eratosthenes and the range() functions I detailed a while back. Hurray for function composition!

function factors(number) {
    const primes = sieve(range(2, number >> 1)).filter(n => !(number % n));
    return primes.length ? primes : [number];

The code is simple:

  1. Generate a list of primes in range 2-(n / 2) (inclusive).
  2. Filter the list to remove numbers that aren’t multiples of n.
  3. If the list is empty, then n is a prime.

To test:

factors(12345); // [3, 5, 823]

This is a dumb brute force solution, but eh, it works. ¯\_(ツ)_/¯

Remap a JavaScript Object

in code

Blog Silence

in me

Run Clare 2019 Race Series

in running

Your email address will not be published. Required fields are marked *