Prime numbers in a range - JavaScript


We are required to write a JavaScript function that takes in two numbers, say, a and b and returns the total number of prime numbers between a and b (including a and b, if they are prime).

For example −

If a = 2, and b = 21, the prime numbers between them are 2, 3, 5, 7, 11, 13, 17, 19

And their count is 8. Our function should return 8.

Let’s write the code for this function −

Example

Following is the code −

const isPrime = num => {
   let count = 2;
   while(count < (num / 2)+1){
      if(num % count !== 0){
         count++;
         continue;
      };
      return false;
   };
   return true;
};
const primeBetween = (a, b) => {
   let count = 0;
   for(let i = Math.min(a, b); i <= Math.max(a, b); i++){
      if(isPrime(i)){
         count++;
      };
   };
   return count;
};
console.log(primeBetween(2, 21));

Output

Following is the output in the console −

8


Updated on: 15-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements