First digit in factorial of a number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program the finds the first digit of a factorial. Let's see an example.

Input − 7

Output − 5

Let's see the steps to solve the problem.

  • Initialize the number

  • Find the factorial of the number.

  • Divide the number until it becomes a single digit.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findFirstDigitOfFactorial(int n) {
   long long int fact = 1;
   for (int i = 2; i <= n; i++) {
      fact = fact * i;
   }
   while (fact >= 10) {
      fact = fact / 10;
   }
   cout << fact << endl;
}
int main() {
   int n = 7;
   findFirstDigitOfFactorial(n);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

5

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 11:03:47
Advertisements