C++ program to find first digit in factorial of a number

Server Side ProgrammingProgramming

In this article, we will be discussing a program to find the first digit in the factorial of a given number.

The basic approach for this is to find the factorial of the number and then get its first digit. But since factorials can end up being too large, we would make a small tweak.

At every point we would check for any trailing zeroes and remove if any exists. Since trailing zeroes isn’t having any effect on the first digit; our result won’t change.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int calc_1digit(int n) {
   long long int fact = 1;
   for (int i = 2; i <= n; i++) {
      fact = fact * i;
      //removing trailing zeroes
      while (fact % 10 == 0)
         fact = fact / 10;
   //finding the first digit
   while (fact >= 10)
   fact = fact / 10;
   return fact;
int main() {
   int n = 37;
   cout << "The first digit : " << calc_1digit(n) << endl;
   return 0;


The first digit : 1
Published on 03-Oct-2019 15:16:44