Prime numbers upto n - JavaScript

Let's say, we are required to write a JavaScript function that takes in a number, say n, and returns an array containing all the prime numbers up to n.

For example ? If the number n is 24, then the output should be ?

const output = [2, 3, 5, 7, 11, 13, 17, 19, 23];

Method 1: Basic Prime Check Approach

This approach uses a helper function to check if each number is prime:

const num = 24;

const isPrime = num => {
    let count = 2;
    while(count < (num / 2) + 1) {
        if(num % count !== 0) {
            count++;
            continue;
        }
        return false;
    }
    return true;
};

const primeUpto = num => {
    if(num < 2) {
        return [];
    }
    const res = [2];
    for(let i = 3; i <= num; i++) {
        if(!isPrime(i)) {
            continue;
        }
        res.push(i);
    }
    return res;
};

console.log(primeUpto(num));
[
  2,  3,  5,  7, 11,
  13, 17, 19, 23
]

Method 2: Sieve of Eratosthenes (Optimized)

For larger numbers, the Sieve of Eratosthenes is more efficient:

const sieveOfEratosthenes = (n) => {
    if (n < 2) return [];
    
    // Create array of true values
    const isPrime = new Array(n + 1).fill(true);
    isPrime[0] = isPrime[1] = false;
    
    // Mark non-primes
    for (let i = 2; i * i <= n; i++) {
        if (isPrime[i]) {
            for (let j = i * i; j <= n; j += i) {
                isPrime[j] = false;
            }
        }
    }
    
    // Collect prime numbers
    const primes = [];
    for (let i = 2; i <= n; i++) {
        if (isPrime[i]) {
            primes.push(i);
        }
    }
    return primes;
};

console.log(sieveOfEratosthenes(24));
console.log(sieveOfEratosthenes(50));
[
  2,  3,  5,  7, 11,
  13, 17, 19, 23
]
[
  2,  3,  5,  7, 11, 13, 17,
  19, 23, 29, 31, 37, 41, 43, 47
]

Comparison

Method Time Complexity Best For
Basic Prime Check O(n²) Small numbers (n
Sieve of Eratosthenes O(n log log n) Large numbers (n > 100)

Key Points

  • Prime numbers are natural numbers greater than 1 with exactly two divisors: 1 and themselves
  • The basic approach checks divisibility for each number individually
  • The Sieve method marks multiples of primes as composite, avoiding redundant checks
  • For performance-critical applications with large inputs, use the Sieve of Eratosthenes

Conclusion

Both methods effectively find prime numbers up to n. Use the basic approach for simple cases and the Sieve of Eratosthenes for better performance with larger inputs.

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

697 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements