Finds the prime factors of a given number using the trial division algorithm.
while
loop to iterate over all possible prime factors, starting with 2
.f
, exactly divides n
, add f
to the factors array and divide n
by f
. Otherwise, increment f
by one.const primeFactors = n => {
let a = [],
f = 2;
while (n > 1) {
if (n % f === 0) {
a.push(f);
n /= f;
} else {
f++;
}
}
return a;
};
primeFactors(147); // [3, 7, 7]
Would you like to help us improve 30 seconds of code?Take a quick survey
JavaScript, Math
Generates primes up to a given number, using the Sieve of Eratosthenes.
JavaScript, Math
Implements the Luhn Algorithm, used to validate a variety of identification numbers.
JavaScript, Math
Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit.