Factoring numbers in a few lines of JavaScript
This domain is a number, so it seemed fair to give the number its own page. That page factors whatever you type into it. Here's how the factoring works.
Trial division
function factor(n) {
const out = [];
for (let p = 2; p * p <= n; p += p === 2 ? 1 : 2) {
while (n % p === 0) { out.push(p); n /= p; }
}
if (n > 1) out.push(n);
return out;
}
Try every candidate up to √n and divide each one out as many times as it fits. Whatever is left above 1 at the end must be prime. Skipping even numbers after 2 halves the work.
Why it's fast enough
For n up to 1012, √n is 106, so the worst case (n is prime) is about half a million divisions. A browser does that in a few milliseconds. The page limits input to 1012 for that reason. Past about 9×1015 you'd also need BigInt, because regular numbers stop being exact integers.
Example
factor(482139073) // [13, 37087621]
Two prime factors, so 482139073 is a semiprime. It has exactly four divisors: 1, 13, 37087621 and itself.
For anything bigger, Pollard's rho is the next step up. It's still short, but not "a few lines" anymore.