I missed this optimization in an interview and wanted to review the algebra that allows it:
for(let j = 2; j * j < i; j++){
The line above in the code below, were instead of using j < i
, we use j * j < i
or equivalently, .
Is this basic algebra we learned in grade school that I forgot? Can a reference be provided to an algebra cheat sheet or similar?
// prime-2
// 2 optimizations - odds and square root
function prime2(n){
const primes = [2];
// first optimization is to only check odd numbers ...
not_prime: for(let i = 3; i < n; i += 2){
// second optimization is to only check up to ...
// the square root of j when looking for factors
for(let j = 2; j * j < i; j++){
if(i % j === 0){
continue not_prime;
}
}
primes.push(i);
}
return primes;
}