Finding nearest prime to a specified number in JavaScript

We are required to write a JavaScript function that takes in a number and returns the first prime number that appears after n.

For example: If the number is 24, then the output should be 29.

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

Understanding Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples include 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, etc.

Example

The code for this will be ?

const num = 24;
const isPrime = n => {
    if (n === 1) {
        return false;
    } else if (n === 2) {
        return true;
    } else {
        for (let x = 2; x < n; x++) {
            if (n % x === 0) {
                return false;
            }
        }
        return true;
    }
};
const nearestPrime = num => {
    while (!isPrime(++num)) {};
    return num;
};
console.log(nearestPrime(24));

Output

The output in the console will be ?

29

How It Works

The solution consists of two functions:

  • isPrime(n): Checks if a number is prime by testing divisibility from 2 to n-1
  • nearestPrime(num): Increments the number and tests each subsequent number until a prime is found

Optimized Version

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

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

const nearestPrimeOptimized = num => {
    let candidate = num + 1;
    while (!isPrimeOptimized(candidate)) {
        candidate++;
    }
    return candidate;
};

console.log(nearestPrimeOptimized(24));
console.log(nearestPrimeOptimized(100));
29
101

Conclusion

Finding the nearest prime after a given number involves incrementing the number and checking primality until a prime is found. The optimized version reduces complexity by only checking divisors up to the square root.

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

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements