Listing all the prime numbers upto a specific number in JavaScript

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];

Therefore, let's write the code for this function ?

Method 1: Using Helper Function for Prime Check

This approach uses a helper function to check if a number is prime, then iterates through numbers up to n:

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: Optimized Prime Check Using Square Root

This version improves efficiency by only checking divisors up to the square root of the number:

const primeUptoOptimized = num => {
    if(num < 2) return [];
    
    const isPrimeOptimized = n => {
        if(n <= 1) return false;
        if(n <= 3) return true;
        if(n % 2 === 0 || n % 3 === 0) return false;
        
        for(let i = 5; i * i <= n; i += 6) {
            if(n % i === 0 || n % (i + 2) === 0) {
                return false;
            }
        }
        return true;
    };
    
    const primes = [];
    for(let i = 2; i <= num; i++) {
        if(isPrimeOptimized(i)) {
            primes.push(i);
        }
    }
    return primes;
};

console.log(primeUptoOptimized(30));
[
    2,  3,  5,  7, 11,
   13, 17, 19, 23, 29
]

How It Works

The first method checks each number by testing divisibility from 2 to half the number. The second method uses mathematical optimization:

  • Numbers divisible by 2 or 3 (except 2 and 3 themselves) are not prime
  • All primes greater than 3 can be written as 6k ± 1
  • Only check divisors up to ?n since larger factors would have corresponding smaller factors

Comparison

Method Time Complexity Best For
Helper Function O(n²/2) Small numbers, learning
Square Root Check O(n?n) Larger numbers, efficiency

Conclusion

Both methods successfully find all prime numbers up to a given limit. The optimized version using square root checking is more efficient for larger numbers and follows mathematical principles for prime detection.

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

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements