Array Conversion Approach

This method involves calculating the factorial sequentially and using built-in JavaScript functions to convert the resultant number into an array of digits. The `reduce} method is then used to calculate the sum of these digits, which is straightforward but may result in cost from array formation.

Example: This example demonstrates how to calculate the factorial of a number and then convert it into an array of digits to compute their sum.

Javascript




function factorial(n) {
    let result = 1;
    for (let i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}
 
function sumOfDigitsInFactorial(num) {
    const fact = factorial(num);
    const digits = Array.from(String(fact),
        Number);
    return digits.reduce((sum, digit) =>
        sum + digit, 0);
}
 
const number = 5;
const sum = sumOfDigitsInFactorial(number);
console.log("Sum of digits in factorial:", sum);


Output

Sum of digits in factorial: 3


JavaScript Program to Find the Sum of Digits in a Factorial

Let’s first define the problem before proceeding to a solution. Any positive number less than or equal to n is the product of all positive integers, and the factorial of a non-negative integer n is denoted by n!. For example, 5!, sometimes known as “five factorial,” is equivalent to 5 × 4 × 3 × 2 × 1 = 120. Adding up the digits of a given number’s factorial is our objective.

Examples:

Input: 10
Output: 27

Input: 100
Output: 648

These are the following appraoches:

Table of Content

  • Iterative Approach
  • Recursive Approach
  • Array Conversion Approach

Similar Reads

Iterative Approach

This method calculates factorial using a loop, then iteratively extracts digits from the result, summing them up, offering efficiency in computation and space....

Recursive Approach

...

Array Conversion Approach

The recursive method iteratively calculates the factorial of the given integer by using a function. After taking each digit from the factorial and adding up all of them, it provides a clear and beautiful solution. For big inputs, however, too much recursion may result in stack overflow issues....