JavaScript Program for Count Primes in Ranges

Prime numbers are numbers that have exactly two perfect divisors (1 and themselves). This article explores multiple methods to count prime numbers in a given range using JavaScript. We'll start with basic approaches and then optimize using the Sieve of Eratosthenes algorithm for better performance.

Method 1: Direct Approach (O(N) per number)

This method counts all divisors of a number. If exactly 2 divisors exist, the number is prime.

function isPrime(number) {
    var count = 0;
    for (var i = 1; i 

13 is a Prime number
14 is not a Prime number

This approach has O(N) time complexity per number check, making it inefficient for large ranges.

Method 2: Mathematical Optimization (O(?N) per number)

Since divisors come in pairs, we only need to check up to the square root of N. For each divisor found, we count it twice (the divisor and its pair).

function isPrime(number) {
    if (number == 1) return false;
    var count = 0;
    for (var i = 1; i * i 

67 is a Prime number
99 is not a Prime number

Counting Primes in Range L to R

Using the optimized isPrime function to count all primes in a given range:

function isPrime(number) {
    if (number 

The number of Prime Numbers from 10 to 50 is: 11

Method 3: Sieve of Eratosthenes (Most Efficient)

The Sieve of Eratosthenes is the most efficient algorithm for finding multiple prime numbers. It marks all composite numbers up to a given limit.

function sieveOfEratosthenes(L, R) {
    var sieve = new Array(R + 1).fill(true);
    sieve[0] = sieve[1] = false;
    
    for (var i = 2; i * i 

The number of Prime Numbers from 10 to 50 is: 11
The number of Prime Numbers from 100 to 200 is: 21

Performance Comparison

Method Time Complexity Space Complexity Best For
Direct Approach O(N²) O(1) Small ranges
Mathematical Optimization O(N?N) O(1) Medium ranges
Sieve of Eratosthenes O(N log log N) O(N) Large ranges, multiple queries

Key Points

  • Prime numbers have exactly two divisors: 1 and themselves
  • The number 1 is not considered prime
  • For single prime checks, use the ?N optimization
  • For multiple range queries, Sieve of Eratosthenes is most efficient
  • The sieve preprocesses all primes up to a limit, enabling fast range queries

Conclusion

The Sieve of Eratosthenes offers the best performance for counting primes in ranges with O(N log log N) time complexity. For single number checks, the mathematical approach with O(?N) complexity is sufficient and memory-efficient.

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

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements