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.

Example

Following is the code −

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 < n; x++){
         if(n % x === 0){
            return false;
         }
      }
      return true;
   };
};
const nearestPrime = num => {
   let sum = digitSum(num);
   while(!isPrime(sum)){
      sum++;
   };
   return sum;
};
console.log(nearestPrime(num));

Output

This will produce the following output in console −

29

Updated on: 30-Sep-2020

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements