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