Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements