Calculating the sum of digits of factorial JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number. The function should first calculate the factorial of that number and then it should return the sum of the digits of the calculated factorial.

For example −

For the number 6, the factorial will be 720, so the output should be 9

Example

const factorial = (num) => {
   if (num == 1) return 1;
   return num * factorial(num-1);
};
const sumOfDigits = (num = 1) => {
   const str = num.toString();
   let sum = 0;
   for (var x = -1; ++x < str.length;) {
      sum += +str[x];
   };
   return sum;
};
const sumFactorialDigits = num => sumOfDigits(factorial(num)); console.log(sumFactorialDigits(6));

Output

This will produce the following output −

9
raja
Published on 25-Nov-2020 05:02:46
Advertisements