Here's a well-structured JavaScript implementation that generates a recurring list of prime numbers using a generator function. This approach allows you to retrieve the next prime number in the sequence on demand, making it ideal for scenarios where you want to generate primes incrementally.
✅ Key Features
- Efficient Prime Checking: Uses previously found primes to test the primality of new candidates.
- Optimized Loop: Skips even numbers after 2 to improve performance.
- Infinite Sequence: The generator can be used to retrieve primes indefinitely.
🧠 How It Works
-
Initialization:
- Starts with the first prime number
2.
- Stores previously found primes to use in future checks.
-
Prime Checking:
- For each candidate number, checks divisibility only by primes up to its square root.
- If no such divisor is found, the number is prime.
-
Yielding:
- Each new prime is added to the list and yielded.
💻 JavaScript Code
function* primeGenerator() {
const primes = []; // Store previously found primes
// Yield the first prime number
yield 2;
primes.push(2);
let current = 3; // Start checking from the next odd number
while (true) {
let isPrime = true;
const sqrtCurrent = Math.sqrt(current);
// Check divisibility using previously found primes
for (const prime of primes) {
if (prime > sqrtCurrent) break;
if (current % prime === 0) {
isPrime = false;
break;
}
}
// If current is prime, yield and store it
if (isPrime) {
primes.push(current);
yield current;
}
// Move to the next odd number
current += 2;
}
}
🧪 Example Usage
To retrieve and log the first 10 prime numbers:
const primeGen = primeGenerator();
for (let i = 0; i < 10; i++) {
console.log(primeGen.next().value);
}
Output:
2
3
5
7
11
13
17
19
23
29
You can continue calling .next().value indefinitely to get more primes.
📌 Notes
- This implementation is stateful, maintaining a list of previously found primes for efficiency.
- It avoids redundant checks by only testing divisibility with known primes up to the square root of the candidate number.
- The generator can be used in
for...of loops or manually via .next() as needed.
🛠️ Optional: Limiting Output to a Specific Range
If you'd like to generate primes up to a certain number, you can wrap the generator like this:
function getPrimesUpTo(limit) {
const primes = [];
const gen = primeGenerator();
let nextPrime = gen.next().value;
while (nextPrime <= limit) {
primes.push(nextPrime);
nextPrime = gen.next().value;
}
return primes;
}
// Example
console.log(getPrimesUpTo(50));
// Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
✅ Summary
This solution provides a clean, efficient, and reusable way to generate prime numbers on demand. The generator approach is ideal for building a recurring list of prime numbers and can be easily integrated into larger applications or used for educational purposes.