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.

Understanding Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. We need to check each number in the range to determine if it's prime.

Example

Following is the code −

const isPrime = num => {
    if (num < 2) return false;
    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));
console.log(primeBetween(10, 30));
console.log(primeBetween(1, 10));

Output

8
6
4

How It Works

The isPrime function checks if a number is prime by testing divisibility from 2 up to half the number. If any divisor is found, it returns false. The primeBetween function iterates through the range and counts prime numbers using isPrime.

Optimized Version

Here's a more efficient approach that only checks divisors up to the square root:

const isPrimeOptimized = num => {
    if (num < 2) return false;
    if (num === 2) return true;
    if (num % 2 === 0) return false;
    
    for (let i = 3; i <= Math.sqrt(num); i += 2) {
        if (num % i === 0) return false;
    }
    return true;
};

const primeBetweenOptimized = (a, b) => {
    let count = 0;
    const start = Math.min(a, b);
    const end = Math.max(a, b);
    
    for(let i = start; i <= end; i++){
        if(isPrimeOptimized(i)){
            count++;
        }
    }
    return count;
};

console.log(primeBetweenOptimized(2, 21));
console.log(primeBetweenOptimized(50, 100));
8
10

Conclusion

This solution efficiently counts prime numbers in a given range by checking divisibility. The optimized version reduces computation by only testing divisors up to the square root of each number.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements