Count digits in a factorial in C++

C++Server Side ProgrammingProgramming

We are given an integer value and the task is to first calculate the factorial of a number and then calculate the total number of digits in a result.

What is a factorial number

Factorial of a number is calculated by multiplying the digits in a number while decrementing the value of digit by 1. It is denoted by the symbol ‘!’ i.e. 0!, 1!, 2!, 3!, 5!,....,etc. Factorial of 0! and 1! is always 1.

I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2
      factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6

For Example

Input − factorial(6)
Output − number of digits in factorial(6) is: 3

Explanation − since the factorial value of 6 is 720 and it contains 3 digits therefore, the result is 3

Input − factorial(12)
Output− number of digits in factorial(12) is: 9

Explanation − since the factorial value of 12 is 479001600 and it contains 9 digits therefore, the result is 9.

Approach used in the below program is as follows

  • Input the number of which factorial needs to be calculated .

  • If the number is less than 0 then return 0 because negative number don’t have any factorial value

  • If the number is 1 then return 1 because 1! Is 1 and it has 1 digit.

  • If the number is greater than 1 i.e. starts with 2 or more than create one loop, starting from 2 till it is less than or equals to number

  • Take one temporary variable let’s say d and initialise it with 0 outside the loop and inside the loop keep adding it with the value of log10(i) till every iteration of i.

  • After that, return the floor value of ‘floor(d)+1’

  • Print the result.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
// This function returns the number of digits present in num!
int count_digits(int num){
   // factorial exists only if num <= 0
   if (num < 0){
      return 0;
   }
   // base case
   if (num <= 1){
      return 1;
   }
   // else iterate through num and calculate the
   // value
   double d = 0;
   for (int i=2; i<=num; i++){
      d += log10(i);
   }
   return floor(d) + 1;
}
int main(){
   cout<<"number of digits in factorial(1) is: "<<count_digits(1)<< endl;
   cout<<"number of digits in factorial(6) is: "<<count_digits(6) << endl;
   cout<<"number of digits in factorial(106) is: "<<count_digits(106) << endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

number of digits in factorial(1) is: 1
number of digits in factorial(6) is: 3
number of digits in factorial(106) is: 171
raja
Published on 15-May-2020 08:50:36
Advertisements