1. Overview

In this tutorial, we’ll discuss an efficient approach to find the sum of digits in the factorial of a number. We’ll also present an algorithm and discuss the steps in detail.

2. Problem Statement

Given a number N, we need to find the factorial of the number N and then add the digits in the factorial.

Let’s take an example to understand the problem and the expected output. We’re taking a random number \mathsf{9}. So here N=9. The first step is to calculate the factorial of \mathsf{9}.

The general formula for calculating the factorial of a number N is N! = 1 \times 2 \times 3\times ..... \times N. Now here N =9:

    \[9! = 1 \times 2 \times 3 \times 4 \times 5 \times 6 \times 7 \times 8 \times 9 = 362880\]

The final step is to add the digits in the factorial.  For this example, the final result would be:

    \[(3 + 6 + 2 + 8 + 8 + 0) = 27\]

3. Our Approach

Given a number N, we’ll calculate factorial using the previous formula. Next, we’ll take the factorial and find the last digit of the factorial. As soon as we find the last digit of the factorial, we’ll store it in a temporary variable (e.g., result) and remove the last digit from the factorial. We’ll repeat this process and continue adding the digits:


4. Pseudocode

Now let’s see the pseudocode:

algorithm SumFactorial(N):
    // INPUT
    //   N = a positive integer number
    // OUTPUT
    //   Sum of digits in the factorial of N

    factorial <- 1
    result <- 0

    for k <- 1 to N:
        factorial <- factorial * k

    while factorial != 0:
        last_digit <- factorial mod 10
        result <- result + last_digit
        factorial <- factorial / 10

    return result

Here we’re taking an integer number N as an input. We use a variable factorial to store the factorial of the input N. The variable last\_digit stores the last digits of the factorial. Finally, we’re adding the digits in the factorial of N in the variable result.

Now to remove the last digit from the factorial at every iteration, we divide it with 10 and reassign the quotient in factorial.

5. Conclusion

In this tutorial, we showed how to find the sum of digits of a factorial. We discussed our approach and presented an algorithm to achieve the solution to the given problem.

Comments are closed on this article!