Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App

Count digits in a factorial using Logarithm

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. ?> 

Output
1 3 7 199

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.

  1. 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.
  2. 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. 
  3. where M_E is the mathematical constant Euler number [Tex]e[/Tex], and M_PI is the mathematical constant [Tex]\pi[/Tex].
  4. 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)); 

Output
1 3 7 199

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.
 



A

Ashutosh Kumar
Improve
Article Tags :
  • DSA
  • Mathematical
  • factorial
  • number-digits
Practice Tags :
  • factorial
  • Mathematical

Similar Reads

  • Factorial of a Number
    Given the number n (n >=0), find its factorial. Factorial of n is defined as 1 x 2 x ... x n. For n = 0, factorial is 1. We are going to discuss iterative and recursive programs in this post. Examples: Input: n = 5Output: 120Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120 Input: n = 4Output: 24Explanat
    7 min read
  • Legendre's formula - Largest power of a prime p in n!
    Given an integer n and a prime number p, the task is to find the largest x such that px (p raised to power x) divides n!. Examples: Input: n = 7, p = 3Output: x = 2Explanation: 32 divides 7! and 2 is the largest such power of 3. Input: n = 10, p = 3Output: x = 4Explanation: 34 divides 10! and 4 is t
    6 min read
  • Count trailing zeroes in factorial of a number
    Given an integer n, write a function that returns count of trailing zeroes in n!. Examples : Input: n = 5Output: 1 Explanation: Factorial of 5 is 120 which has one trailing 0. Input: n = 20Output: 4Explanation: Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100Output:
    8 min read
  • Find the Factorial of a large number
    Factorial of a non-negative integer, is the multiplication of all integers smaller than or equal to n. Examples: Input: 100Output: 933262154439441526816992388562667004- 907159682643816214685929638952175999- 932299156089414639761565182862536979- 208272237582511852109168640000000000- 00000000000000 In
    15+ min read
  • Primorial of a number
    Given a number n, the task is to calculate its primorial. Primorial (denoted as Pn#) is a product of first n prime numbers. Primorial of a number is similar to the factorial of a number. In primorial, not all the natural numbers get multiplied only prime numbers are multiplied to calculate the primo
    10 min read
  • Find maximum power of a number that divides a factorial
    Given two numbers, fact and n, find the largest power of n that divides fact! (Factorial of fact). Examples: Input : fact = 5, n = 2 Output : 3 Explanation: Value of 5! is 120. The largest power of 2 that divides 120 is 8 (or 23 Input : fact = 146, n = 15 Output : 35 The idea is based on Legendre’s
    12 min read
  • Largest power of k in n! (factorial) where k may not be prime
    Given two numbers k and n, find the largest power of k that divides n! Constraints: K > 1 Examples: Input : n = 7, k = 2Output : 4Explanation : 7! = 5040The largest power of 2 that divides 5040 is 24.Input : n = 10, k = 9Output : 2The largest power of 9 that divides 10! is 92. [Naive Approach] Fa
    12 min read
  • Check if a number is a Krishnamurthy Number or not
    A Krishnamurthy number is a number whose sum of the factorial of digits is equal to the number itself.For example, 145 is the sum of the factorial of each digit.1! + 4! + 5! = 1 + 24 + 120 = 145 Examples: Input : 145Output : YESExplanation: 1! + 4! + 5! = 1 + 24 + 120 = 145, which is equal to input,
    10 min read
  • Last non-zero digit of a factorial
    Given a number n, find the last non-zero digit in n!.Examples: Input : n = 5 Output : 2 5! = 5 * 4 * 3 * 2 * 1 = 120 Last non-zero digit in 120 is 2. Input : n = 33 Output : 8 Recommended PracticeLast non-zero digit in factorialTry It! A Simple Solution is to first find n!, then find the last non-ze
    14 min read
  • Count digits in a factorial using Logarithm
    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: 5Output: 3Explanation: 5! = 120, i.e., 3 digits Input: 10Output: 7Explanation: 10! = 3628800, i.e., 7 digits Naive approa
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences