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

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 <= Math.sqrt(max + 1); i++) {
      for (let j = i ** 2; j < max + 1; j += i) delete result[j];
   }
   return Object.values(result.slice(min));
};
const getRandomNum = (min, max) => {
   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

And the output in the console will be −

311

Output is likely to differ in each run.

Updated on: 21-Nov-2020

410 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements