For a function that takes an integer n
and returns an array of the first n
primes, we have:
function nPrimes(n) {
let primes = [];
for(let i = 3; primes.length < n - 1; i += 2) {
if (primes.every(prime => i % prime !== 0)) {
primes.push(i);
}
}
primes.unshift(2);
return primes;
}
I'm not sure what the complexity of this algorithm would be. It seems at least quadratic, because the every
call adds one n
to the runtime complexity where n is the size of the primes array at a given iteration. The unshift
at the end adds an n
but is irrelevant because it will be dwarfed by the leading coefficient.
The follow up is, is there a more efficient way of generating such an array?