1. Divisors to sqrt
Try divisors only up to sqrt(n); a larger factor leaves a small cofactor.
for (let d = 2; d * d <= n; d += 1)Typorithm · medium
Step 1 of 8 · intro card
Math & Number Theory
Trial-divide by every candidate up to sqrt(n), pulling out each factor; any leftover is prime.
Trial division tests divisors from 2 upward, removing each factor completely before moving on.
Once a divisor d satisfies d*d > n, the remaining n (if above 1) must itself be prime.
Dividing n down as you go keeps the loop bound small and the work near sqrt(n).
Divide out every copy of d.
Loop only while d*d <= n.
Leftover n > 1 is prime.
function primeFactors(n) {
const factors = [];
for (let d = 2; d * d <= n; d += 1) {
while (n % d === 0) {
factors.push(d);
n = n / d;
}
}
if (n > 1) {
factors.push(n);
}
return factors;
}Connect each part of the code to the concept before you type.
Try divisors only up to sqrt(n); a larger factor leaves a small cofactor.
for (let d = 2; d * d <= n; d += 1)Pull out every copy of the current divisor.
while (n % d === 0)Each exact division records one prime factor.
factors.push(d)Dividing n keeps the search space small.
n = n / dAny value above 1 left at the end is itself a prime factor.
if (n > 1)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputFactorize 84
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state