Open In App

JavaScript Program to Find the Sum of Digits in a Factorial

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

Example: The factorial() method uses an iterative approach to determine the factorial, but the sumOfDigitsInFactorial() function extracts each digit from the factorial using modulus division and divides the result by 10. Until no more digits can be removed, this process is repeated.

Javascript




function factorial(n) {
    let result = 1;
    // Calculate the factorial
    // using a for loop from 2 to n.
    for (let i = 2; i <= n; i++) {
        result *= i;
    }
    // Return the factorial result.
    return result;
}
 
function sumOfDigitsInFactorial(num) {
    let fact = factorial(num);
    let sum = 0;
    while (fact !== 0) {
        sum += fact % 10;
        fact = Math.floor(fact / 10);
    }
    return sum;
}
 
const num = 5;
const sumOfDigits = sumOfDigitsInFactorial(num);
console.log("Sum of digits in factorial:",
    sumOfDigits);


Output

Sum of digits in factorial: 3

Recursive 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.

Example: The `factorial` function calculates the factorial of a number recursively. The `sumOfDigitsInFactorial` function computes the sum of digits in the factorial of a given number by iterating through its digits using a while loop. The example calculates and prints the sum of digits in the factorial of 5.

Javascript




function factorial(n) {
    if (n === 0 || n === 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}
 
function sumOfDigitsInFactorial(num) {
    let fact = factorial(num);
    let sum = 0;
    while (fact !== 0) {
        sum += fact % 10;
        fact = Math.floor(fact / 10);
    }
    return sum;
}
 
const num = 5;
const sumOfDigits = sumOfDigitsInFactorial(num);
console.log("Sum of digits in factorial:",
    sumOfDigits);


Output

Sum of digits in factorial: 3

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


Previous Article
Next Article

Similar Reads

JavaScript Program to Find Factorial of a Number using Recursion
In this article, we are going to learn about finding a Factorial of a Number using Recursion. Calculating the factorial of a number using recursion means implementing a function that calls itself to find the factorial of a given number. The factorial of a non-negative integer "n" is the product of all positive integers less than or equal to "n". Th
2 min read
JavaScript Program to Count Trailing Zeroes in Factorial of a Number
In this article, we are going to learn how to count trailing zeroes in the factorial of a number in JavaScript. Counting trailing zeroes in the factorial of a number means determining how many consecutive zeros appear at the end of the factorial's decimal representation. It's a measure of how many times the factorial value is divisible by 10. Examp
3 min read
Factorial Calculator Card using Tailwind CSS and JavaScript
The Factorial Calculator is a web application designed to calculate the factorial of a non-negative integer entered by the user and instantly compute its factorial upon a button click. If the user wants to start over, they can utilize the "Clear" button. Its design and user-friendly features ensure a smooth user experience. Approach to create Facto
3 min read
Factorial of a number using JavaScript
The factorial of a non-negative integer is the product of all positive integers less than or equal to that number. It's denoted by "n!" where n is the integer. Factorial represents the number of permutations or arrangements of a set. Note: Factorials of negative numbers are not defined as only positive numbers including 0 are defined in the domain
2 min read
PHP Program to Count trailing zeroes in factorial of a number
Given an integer n, write a function that returns count of trailing zeroes in n!. Examples : Input: n = 5 Output: 1 Factorial of 5 is 120 which has one trailing 0. Input: n = 20 Output: 4 Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100 Output: 24Trailing 0s in n! = Count of 5s in prime factors of n! = floor(n/5) +
1 min read
JavaScript Program for Sum of Number Digits in a Linked List
We are going to write a JavaScript program on how to find the sum of number digits stored in a linked list. We are going to use the Iterative and Recursive techniques to find the Sum of number digits. A linked list is a data structure where elements are stored in nodes and each node points to the next node in the sequence. Table of Content Iterativ
2 min read
JavaScript Program for Sum of Digits of a Number using Recursion
We are given a number as input and we have to find the sum of all the digits contained by it. We will split the digits of the number and add them together using recursion in JavaScript. Table of Content Recursively Summing DigitsUsing string manipulation with recursionRecursively Summing DigitsIn this approach, we define a recursive function that t
2 min read
JavaScript Program for Sum of Digits of a Number
In this article, we are going to learn about finding the Sum of Digits of a number using JavaScript. The Sum of Digits refers to the result obtained by adding up all the individual numerical digits within a given integer. It's a basic arithmetic operation. This process is repeated until a single-digit sum, also known as the digital root. There are
3 min read
Javascript Program to Find Maximum value possible by rotating digits of a given number
Given a positive integer N, the task is to find the maximum value among all the rotations of the digits of the integer N. Examples: Input: N = 657Output: 765Explanation: All rotations of 657 are {657, 576, 765}. The maximum value among all these rotations is 765. Input: N = 7092Output: 9270Explanation:All rotations of 7092 are {7092, 2709, 9270, 09
2 min read
PHP | Factorial of a number
We already know how to get the factorial of a number in other languages. Let's see how this is done in PHP using both recursive and non-recursive ways. Examples: Input : 5 Output : 120 Input : 10 Output : 3628800 Method 1: Iterative way In this method, we simply used the for loop to iterate over the sequence of numbers to get the factorial. C/C++ C
2 min read