loading...

re: Daily Challenge #269 - Decompose n! VIEW POST

FULL DISCUSSION
 

bit.ly/3j2UpqA

const isPrime = (number) => {
  let list = [...Array(Math.floor(number ** 0.5)).keys()]
    .map((x) => x + 1)
    .slice(1);
  return !list.some((n) => number % n === 0);
};

const findPrimes = (number) =>
  [...Array(number + 1).keys()].slice(2).filter((n) => isPrime(n));

const factorize = (number, prime) => {
  let result = 0;
  for (let i = number; i >= prime; ) {
    let div = Math.floor(i / prime);
    result += div;
    i = div;
  }

  return result > 1 ? `${prime}^${result}` : `${prime}`;
};

const decomp = (n) =>
  findPrimes(n)
    .map((prime) => factorize(n, prime))
    .join(" * ");


 

You can check for divisors in [2;ceiling(sqrt(n))], that should be way faster for large n

Code of Conduct Report abuse