First of all, thanks for putting in all that effort and then sharing it with the community โค๏ธ
I was thinking about contributing some of the missing bits, although I'm unsure how far I should go with some solutions. And, is my appraoch aligned with your visions and goals for this initiative.
For example, I was looking at "Verify a prime number?". Now the current solution is-
const isPrime = (num) => {
for (let i = 2; i < num; i++) if (num % i === 0) return false;
return num > 1;
};
There are a few things we can do here:
- Replace this version with a bit efficient version.
- Add a step-by-step example of how we can improve it.
- Replace this version with the most efficient version.
- Add external resources.
Keen to know your thoughts. Which one would you prefer?
Here's a version I'm fiddling with now:
The simplest approach is to check if num is divisible by every integer less than num.
const isPrime = (num) => {
for (let i = 2; i < num; i++) if (num % i === 0) return false;
return num > 1;
};
A more efficient approach is to check if the num is divisible by every integer up to its square root.
Should we explain why one of the factors should always be less or equal to the square root of a number?
const isPrime = (num) => {
const limit = Math.sqrt(num);
for (let i = 2; i <= limit; i++) if (num % i === 0) return false;
return num > 1;
};
A slightly more efficient approach is also to avoid all even numbers since they are divisible by 2; hence can't be prime.
const isPrime = (num) => {
if (num % 2 === 0) return num === 2;
const limit = Math.sqrt(num);
for (let i = 3; i <= limit; i+=2)
if (num % i === 0) return false;
return num > 1;
};
We can keep creating slightly more efficient versions by eliminating multiples of known primes.
- Should we explain how they can derive this from
6k + i
or even write more efficient versions following the same pattern (p1 * p2 * ... * pn)k + i
?
const isPrime = (num) => {
if (num % 2 === 0) return num === 2;
if (num % 3 === 0) return num === 3;
const limit = Math.sqrt(num);
for (let i = 5; i <= limit; i+=6)
if (num % i === 0 || num % (i + 2) === 0) return false;
return num > 1;
};
Here's the result of not very scientific benchmark I did ๐