Prime numbers within a range in 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 = 21, and b = 38.

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

  • And their count is 4

  • Our function should return 4

Understanding Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Numbers like 2, 3, 5, 7, 11 are prime, while 4, 6, 8, 9 are not.

Solution Approach

We'll create two functions:

  • isPrime() - checks if a single number is prime
  • primeBetween() - counts primes in a range using isPrime()

Example

const isPrime = num => {
    if (num  {
    let count = 0;
    for (let i = Math.min(a, b); i 

4
4
4

How It Works

The isPrime() function uses an optimized algorithm:

  • Numbers ? 1 are not prime
  • 2 and 3 are prime
  • Numbers divisible by 2 or 3 are not prime
  • Check divisors of form 6k±1 up to ?num for efficiency

Alternative: Simple Approach

Here's a simpler but less efficient version for educational purposes:

const isPrimeSimple = num => {
    if (num  {
    let count = 0;
    let primes = [];
    
    for (let i = Math.min(a, b); i 

Prime numbers found: [ 23, 29, 31, 37 ]
Count: 4

Performance Comparison

Approach Time Complexity Best For
Simple Check O(?n) per number Small ranges, learning
Optimized Check O(?n/3) per number Large ranges, production

Conclusion

This solution efficiently counts prime numbers in any range by combining a prime-checking function with range iteration. The optimized version handles larger numbers more efficiently by reducing the number of divisibility checks.

Updated on: 2026-03-15T23:19:00+05:30

753 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements