Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generating Random Prime Number in JavaScript
We are required to write a JavaScript function that takes in two numbers specifying a range. Our function should return a random prime number that falls in that range.
Algorithm Overview
The solution uses the Sieve of Eratosthenes algorithm to find all prime numbers in the range, then randomly selects one. This approach ensures efficiency for finding multiple primes.
Example
The code for this will be ?
const range = [100, 1000];
const getPrimes = (min, max) => {
const result = Array(max + 1)
.fill(0)
.map((_, i) => i);
for (let i = 2; i {
return Math.floor(Math.random() * (max - min + 1) + min);
};
const getRandomPrime = ([min, max]) => {
const primes = getPrimes(min, max);
return primes[getRandomNum(0, primes.length - 1)];
};
console.log(getRandomPrime(range));
Output
The output in the console will be ?
311
Output is likely to differ in each run since we're selecting a random prime from the range.
How It Works
The getPrimes() function implements the Sieve of Eratosthenes:
- Creates an array from 0 to max
- Marks multiples of each prime as composite (deletes them)
- Returns remaining numbers (primes) in the specified range
The getRandomPrime() function then picks a random index from the primes array.
Testing with Different Ranges
// Test with smaller range
console.log("Prime between 10-50:", getRandomPrime([10, 50]));
// Test with larger range
console.log("Prime between 500-1000:", getRandomPrime([500, 1000]));
// Multiple calls to show randomness
console.log("Multiple calls:");
for (let i = 0; i
Prime between 10-50: 37
Prime between 500-1000: 743
Multiple calls:
109
137
167
191
149
Conclusion
This solution efficiently generates random prime numbers using the Sieve of Eratosthenes algorithm. The approach works well for moderate ranges and ensures truly random selection from all available primes.
