Was it helpful?

Question

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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 30-Sep-2020 17:17:58
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top