Calculating the sum of digits of factorial JavaScript

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 sum of digits (7 + 2 + 0) should be 9.

Understanding the Problem

This problem involves two steps:

  • Calculate the factorial of a given number
  • Sum all digits in the factorial result

Step 1: Calculate Factorial

First, we need a function to calculate factorial using recursion:

const factorial = (num) => {
    if (num <= 1) return 1;
    return num * factorial(num - 1);
};

console.log(factorial(6)); // Test factorial calculation
720

Step 2: Sum of Digits

Next, we create a function to sum all digits in a number by converting it to a string and iterating through each digit:

const sumOfDigits = (num) => {
    const str = num.toString();
    let sum = 0;
    for (let i = 0; i < str.length; i++) {
        sum += parseInt(str[i]);
    }
    return sum;
};

console.log(sumOfDigits(720)); // Test with factorial of 6
9

Complete Solution

Now we combine both functions to solve the complete problem:

const factorial = (num) => {
    if (num <= 1) return 1;
    return num * factorial(num - 1);
};

const sumOfDigits = (num) => {
    const str = num.toString();
    let sum = 0;
    for (let i = 0; i < str.length; i++) {
        sum += parseInt(str[i]);
    }
    return sum;
};

const sumFactorialDigits = (num) => {
    const fact = factorial(num);
    console.log(`Factorial of ${num} is: ${fact}`);
    return sumOfDigits(fact);
};

// Test with different numbers
console.log(`Sum of digits: ${sumFactorialDigits(6)}`);
console.log(`Sum of digits: ${sumFactorialDigits(5)}`);
console.log(`Sum of digits: ${sumFactorialDigits(4)}`);
Factorial of 6 is: 720
Sum of digits: 9
Factorial of 5 is: 120
Sum of digits: 3
Factorial of 4 is: 24
Sum of digits: 6

Alternative Approach Using Array Methods

We can also solve this using modern JavaScript array methods for a more functional approach:

const sumFactorialDigitsAlternative = (num) => {
    const factorial = (n) => n <= 1 ? 1 : n * factorial(n - 1);
    
    return factorial(num)
        .toString()
        .split('')
        .reduce((sum, digit) => sum + parseInt(digit), 0);
};

console.log(sumFactorialDigitsAlternative(6));
console.log(sumFactorialDigitsAlternative(7));
9
15

Conclusion

This solution efficiently calculates the factorial of a number and then sums its digits using string manipulation. The recursive factorial function handles the mathematical computation, while the digit sum function processes the result as a string for easy digit extraction.

Updated on: 2026-03-15T23:19:00+05:30

567 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements