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
Prime digits sum of a number in JavaScript
We are required to write a JavaScript function that takes in a number as the first and the only argument. The function should then sum all the digits of the number that are prime and return the sum as a number.
For example −
If the input number is −
const num = 67867852;
Then the output should be −
const output = 21;
because 7 + 7 + 5 + 2 = 21 −
Example
Following is the code −
const num = 67867852;
const sumPrimeDigits = (num) => {
const primes = '2357';
let sum = 0;
while(num){
const digit = num % 10;
if(primes.includes('' + digit)){
sum += digit;
};
num = Math.floor(num / 10);
};
return sum;
};
console.log(sumPrimeDigits(num));
Output
Following is the console output −
21
Advertisements