Count digits in a factorial using Logarithm
Last Updated :
23 Jul, 2025
Given an integer N, find the number of digits that appear in its factorial, where factorial is defined as, factorial(n) = 1*2*3*4........*n and factorial(0) = 1
Examples :
Input: 5
Output: 3
Explanation: 5! = 120, i.e., 3 digits
Input: 10
Output: 7
Explanation: 10! = 3628800, i.e., 7 digits
Naive approach: To solve the problem follow the below idea:
A naive solution would be to calculate the n! first and then calculate the number of digits present in it. However as the value for n! can be very large, it would become cumbersome to store them in a variable (Unless you're working in python!).
Count digits in a factorial using the property of logarithms:
To solve the problem follow the below idea:
We know,
log(a*b) = log(a) + log(b)
Therefore
log( n! ) = log(1*2*3....... * n) = log(1) + log(2) + ........ +log(n)
Now, observe that the floor value of log base
10 increased by 1, of any number, gives the
number of digits present in that number.
Hence, output would be : floor(log(n!)) + 1.
Below is the implementation of the above approach:
C++
// A C++ program to find the number of digits in
// a factorial
#include <bits/stdc++.h>
using namespace std;
// This function receives an integer n, and returns
// the number of digits present in n!
int findDigits(int n)
{
// factorial exists only for n>=0
if (n < 0)
return 0;
// base case
if (n <= 1)
return 1;
// else iterate through n and calculate the
// value
double digits = 0;
for (int i = 2; i <= n; i++)
digits += log10(i);
return floor(digits) + 1;
}
// Driver code
int main()
{
// Function call
cout << findDigits(1) << endl;
cout << findDigits(5) << endl;
cout << findDigits(10) << endl;
cout << findDigits(120) << endl;
return 0;
}
Java
// Java program to find the number
// of digits in a factorial
import java.io.*;
import java.util.*;
class GFG {
// returns the number of digits
// present in n!
static int findDigits(int n)
{
// factorial exists only for n>=0
if (n < 0)
return 0;
// base case
if (n <= 1)
return 1;
// else iterate through n and calculate the
// value
double digits = 0;
for (int i = 2; i <= n; i++)
digits += Math.log10(i);
return (int)(Math.floor(digits)) + 1;
}
// Driver code
public static void main(String[] args)
{
// Function call
System.out.println(findDigits(1));
System.out.println(findDigits(5));
System.out.println(findDigits(10));
System.out.println(findDigits(120));
}
}
// This code is contributed by Pramod Kumar
Python
# Python3 program to find the
# number of digits in a factorial
import math
# This function receives an integer
# n, and returns the number of
# digits present in n!
def findDigits(n):
# factorial exists only for n>=0
if (n < 0):
return 0
# base case
if (n <= 1):
return 1
# else iterate through n and
# calculate the value
digits = 0
for i in range(2, n + 1):
digits += math.log10(i)
return math.floor(digits) + 1
# Driver code
if __name__ == "__main__":
print(findDigits(1))
print(findDigits(5))
print(findDigits(10))
print(findDigits(120))
# This code is contributed by mits
C#
// A C# program to find the number
// of digits in a factorial
using System;
class GFG {
// This function receives an integer
// n, and returns the number of
// digits present in n!
static int findDigits(int n)
{
// factorial exists only for n>=0
if (n < 0)
return 0;
// base case
if (n <= 1)
return 1;
// else iterate through n and
// calculate the value
double digits = 0;
for (int i = 2; i <= n; i++)
digits += Math.Log10(i);
return (int)Math.Floor(digits) + 1;
}
// Driver code
public static void Main()
{
// Function call
Console.Write(findDigits(1) + "\n");
Console.Write(findDigits(5) + "\n");
Console.Write(findDigits(10) + "\n");
Console.Write(findDigits(120) + "\n");
}
}
// This code is contributed by
// Smitha Dinesh Semwal
JavaScript
// A Javascript program to find the number of digits in
// a factorial
// This function receives an integer n, and returns
// the number of digits present in n!
function findDigits(n)
{
// factorial exists only for n>=0
if (n < 0)
return 0;
// base case
if (n <= 1)
return 1;
// else iterate through n and calculate the
// value
let digits = 0;
for (let i=2; i<=n; i++)
digits += Math.log10(i);
return Math.floor(digits) + 1;
}
// Driver code
document.write(findDigits(1) + "<br>");
document.write(findDigits(5) + "<br>");
document.write(findDigits(10) + "<br>");
document.write(findDigits(120) + "<br>");
//This code is contributed by Mayank Tyagi
PHP
<?php
// PHP program to find
// the number of digits
// in a factorial
// This function receives
// an integer n, and returns
// the number of digits present in n!
function findDigits($n)
{
// factorial exists only for n>=0
if ($n < 0)
return 0;
// base case
if ($n <= 1)
return 1;
// else iterate through n and
// calculate the value
$digits = 0;
for ($i = 2; $i <= $n; $i++)
$digits += log10($i);
return floor($digits) + 1;
}
// Driver code
// Function call
echo findDigits(1), "\n";
echo findDigits(5), "\n";
echo findDigits(10), "\n";
echo findDigits(120), "\n";
// This code is contributed by Ajit.
?>
Time complexity: O(N log N) since calculating log in a loop
Auxiliary space: O(1) because it is using constant variables
Approach 2: Using Stirling's approximation formula to calculate the factorial and logarithm to count the number of digits.
- The countDigitsInFactorial(int n) function takes an integer n as input and returns the number of digits in the factorial of n. If n is negative, it returns 0. If n is 0 or 1, the factorial is 1, and it returns 1.
- In the countDigitsInFactorial(int n) function, the double x variable is declared and initialized using the Stirling's approximation formula for the factorial. This formula provides a good approximation of the value of the factorial for large values of n.
- where M_E is the mathematical constant Euler number e, and M_PI is the mathematical constant \pi.
- The formula used in this code is a simplified version of Stirling's approximation that takes the logarithm of the above formula to get the number of digits in the factorial.
C++
#include <cmath>
#include <iostream>
using namespace std;
int countDigitsInFactorial(int n)
{
if (n < 0) {
return 0;
}
if (n <= 1) {
return 1;
}
double x
= (n * log10(n / M_E) + log10(2 * M_PI * n) / 2.0);
return floor(x) + 1;
}
int main()
{
cout << countDigitsInFactorial(1) << endl;
cout << countDigitsInFactorial(5) << endl;
cout << countDigitsInFactorial(10) << endl;
cout << countDigitsInFactorial(120) << endl;
return 0;
}
Java
// Java implementation of above approach
import java.lang.Math;
import java.util.Scanner;
public class Solution {
public static int countDigitsInFactorial(int n) {
// factorial exists only for n>=0
if (n < 0) {
return 0;
}
if (n <= 1) {
return 1;
}
// Calculating the digit's values
double x = (n * Math.log10(n / Math.E) + Math.log10(2 * Math.PI * n) / 2.0);
// returning the floor value + 1
return (int) Math.floor(x) + 1;
}
public static void main(String[] args) {
// calling the countDigitInFactorial function
System.out.println(countDigitsInFactorial(1));
System.out.println(countDigitsInFactorial(5));
System.out.println(countDigitsInFactorial(10));
System.out.println(countDigitsInFactorial(120));
}
}
Python
import math
def countDigitsInFactorial(n):
if n < 0:
return 0
if n <= 1:
return 1
# Using Stirling's approximation formula to count the number of digits
x = (n * math.log10(n / math.e) + math.log10(2 * math.pi * n) / 2.0)
# Floor the result of the formula and add 1 to get the number of digits
return math.floor(x) + 1
# Testing the function with sample inputs
print(countDigitsInFactorial(1))
print(countDigitsInFactorial(5))
print(countDigitsInFactorial(10))
print(countDigitsInFactorial(120))
C#
using System;
public class Program {
static int CountDigitsInFactorial(int n)
{
if (n < 0) {
return 0;
}
if (n <= 1) {
return 1;
}
double x = (n * Math.Log10(n / Math.E)
+ Math.Log10(2 * Math.PI * n) / 2.0);
return (int)Math.Floor(x) + 1;
}
public static void Main()
{
Console.WriteLine(CountDigitsInFactorial(1));
Console.WriteLine(CountDigitsInFactorial(5));
Console.WriteLine(CountDigitsInFactorial(10));
Console.WriteLine(CountDigitsInFactorial(120));
}
}
JavaScript
// Javascript program for the above approach
// Function to count digits in factorials
// of the number n
function countDigitsInFactorial(n) {
if (n < 0) {
return 0;
}
if (n <= 1) {
return 1;
}
let x = n * Math.log10(n / Math.E) + Math.log10(2 * Math.PI * n) / 2.0;
return Math.floor(x) + 1;
}
// Driver Code
console.log(countDigitsInFactorial(1));
console.log(countDigitsInFactorial(5));
console.log(countDigitsInFactorial(10));
console.log(countDigitsInFactorial(120));
Time complexity: O(1)
The time complexity of the above approach to count the number of digits in n! using Stirling's approximation and logarithms is O(1), meaning it is constant time complexity.
Auxiliary space: O(1)
In the next set, we'd see how to further optimize our approach and reduce the time complexity for the same program.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem