JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript

We are required to write a JavaScript function that takes in a number, finds the sum of its digits and returns a prime number that is just greater than or equal to the sum.

Understanding the Problem

For a number like 56563, we first calculate the sum of digits: 5 + 6 + 5 + 6 + 3 = 25. Since 25 is not prime (divisible by 5), we find the next prime number, which is 29.

Example

const num = 56563;

const digitSum = (num, sum = 0) => {
    if(num){
        return digitSum(Math.floor(num / 10), sum + (num % 10));
    }
    return sum;
};

const isPrime = n => {
    if (n === 1){
        return false;
    } else if(n === 2){
        return true;
    } else {
        for(let x = 2; x  {
    let sum = digitSum(num);
    while(!isPrime(sum)){
        sum++;
    }
    return sum;
};

console.log("Number:", num);
console.log("Sum of digits:", digitSum(num));
console.log("Nearest prime:", nearestPrime(num));
Number: 56563
Sum of digits: 25
Nearest prime: 29

How It Works

The solution consists of three functions:

  • digitSum() - Recursively calculates the sum of digits by dividing by 10 and using modulo to get individual digits
  • isPrime() - Checks if a number is prime by testing divisibility from 2 to n-1
  • nearestPrime() - Finds the nearest prime by incrementing the digit sum until a prime is found

Optimized Prime Check

For better performance with larger numbers, we can optimize the prime check by only testing up to the square root:

const isPrimeOptimized = n => {
    if (n  {
    let sum = digitSum(num);
    while(!isPrimeOptimized(sum)){
        sum++;
    }
    return sum;
};

console.log("Optimized result:", nearestPrimeOptimized(56563));
Optimized result: 29

Testing with Different Numbers

const testNumbers = [123, 999, 1111, 7];

testNumbers.forEach(num => {
    const sum = digitSum(num);
    const prime = nearestPrime(num);
    console.log(`Number: ${num}, Digit sum: ${sum}, Nearest prime: ${prime}`);
});
Number: 123, Digit sum: 6, Nearest prime: 7
Number: 999, Digit sum: 27, Nearest prime: 29
Number: 1111, Digit sum: 4, Nearest prime: 5
Number: 7, Digit sum: 7, Nearest prime: 7

Conclusion

This solution efficiently finds the nearest prime number greater than or equal to the sum of digits. The optimized prime check improves performance for larger sums by reducing the number of divisibility tests required.

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

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements