Prime numbers within a range in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 = 21, and b = 38.

  • The prime numbers between them are 23, 29, 31, 37

  • And their count is 4

  • Our function should return 4

Example

The code for this will be −

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(21, 38));

Output

The output in the console −

4
raja
Published on 15-Oct-2020 12:20:12
Advertisements