Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Summing up digits and finding nearest prime in 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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
29
Advertisements
