Answers for "prime factors js"

0

prime factors js

const primeFactors = n => {
    if (n < 2) return `(${n})`;
    let factors = '';
    for ( let i = 2; i <= n; i++) {
        let count = 0;
        while ( n%i === 0 ) {
            count++; 
            n /= i;
        }
        if (count) {
            factors += `(${i}`;
            if (count > 1) factors += `**${count}`;
            factors += `)`;
        }
    }
    return factors;
}
Posted by: Guest on October-16-2021
0

prime factors of an integer js

function primeFactors(n) {
  const factors = [];
  let divisor = 2;

  while (n >= 2) {
    if (n % divisor == 0) {
      factors.push(divisor);
      n = n / divisor;
    } else {
      divisor++;
    }
  }
  return factors;
}

const randomNumber = Math.floor(Math.random() * 10000);
console.log('Prime factors of', randomNumber + ':', primeFactors(randomNumber).join(' '))
 Run code snippet
Posted by: Guest on October-16-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language