Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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
Next Article:
Find the Factorial of a large number
Next article icon

Count trailing zeroes in factorial of a number

Last Updated : 22 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an integer n, write a function that returns count of trailing zeroes in n!. 

Examples : 

Input: n = 5
Output: 1
Explanation: Factorial of 5 is 120 which has one trailing 0.

Input: n = 20
Output: 4
Explanation: Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes.

Input: n = 100
Output: 24

Table of Content

  • [Naive Approach] By calculating the factorial of the number - O(n) Time and O(1) Space
  • [Expected Approach] Repeated division by 5 - O(log n base 5) Time and O(1) Space

[Naive Approach] By calculating the factorial - O(n) Time and O(1) Space

The idea is to calculate the factorial of the number and then count the number of trailing zeros by repeatedly dividing the factorial by 10 till the last digit is 0. The number of times the factorial is divided by 10 is the number of trailing zeros. This approach is not useful for large numbers as calculating their factorial will cause overflow.

C++
#include <iostream> using namespace std;  // Function to calculate factorial of a number int factorial(int n) {     int fact = 1;     for (int i = 1; i <= n; ++i) {         fact *= i;     }     return fact; }  // Function to count trailing zeros in factorial int countTrailingZeros(int n) {     int fact = factorial(n);     int count = 0;      // Count trailing zeros by dividing the factorial by 10     while (fact % 10 == 0) {         count++;         fact /= 10;     }      return count; }  int main() {     int n = 5;     cout << countTrailingZeros(n) << endl;  // Output only the count     return 0; } 
Java
public class Main {      // Function to calculate factorial of a number     public static int factorial(int n) {         int fact = 1;         for (int i = 1; i <= n; ++i) {             fact *= i;         }         return fact;     }      // Function to count trailing zeros in factorial     public static int countTrailingZeros(int n) {         int fact = factorial(n);         int count = 0;          // Count trailing zeros by dividing the factorial by 10         while (fact % 10 == 0) {             count++;             fact /= 10;         }          return count;     }      public static void main(String[] args) {         int n = 5;         System.out.println(countTrailingZeros(n));  // Output only the count     } } 
Python
# Function to calculate factorial of a number def factorial(n):     fact = 1     for i in range(1, n + 1):         fact *= i     return fact  # Function to count trailing zeros in factorial def count_trailing_zeros(n):     fact = factorial(n)     count = 0      # Count trailing zeros by dividing the factorial by 10     while fact % 10 == 0:         count += 1         fact //= 10      return count  # Driver code n = 5 print(count_trailing_zeros(n))  # Output only the count 
C#
using System;  class Program {      // Function to calculate factorial of a number     public static int Factorial(int n) {         int fact = 1;         for (int i = 1; i <= n; ++i) {             fact *= i;         }         return fact;     }      // Function to count trailing zeros in factorial     public static int CountTrailingZeros(int n) {         int fact = Factorial(n);         int count = 0;          // Count trailing zeros by dividing the factorial by 10         while (fact % 10 == 0) {             count++;             fact /= 10;         }          return count;     }      static void Main() {         int n = 5;         Console.WriteLine(CountTrailingZeros(n));  // Output only the count     } } 
JavaScript
// Function to calculate factorial of a number function factorial(n) {     let fact = 1;     for (let i = 1; i <= n; ++i) {         fact *= i;     }     return fact; }  // Function to count trailing zeros in factorial function countTrailingZeros(n) {     let fact = factorial(n);     let count = 0;      // Count trailing zeros by dividing the factorial by 10     while (fact % 10 === 0) {         count++;         fact /= 10;     }      return count; }  // Driver code const n = 5; console.log(countTrailingZeros(n));  // Output only the count 

Output
1 

[Expected Approach] Repeated division by 5 - O(log n base 5) Time and O(1) Space

The idea is to consider all prime factors of factorial n. A trailing zero is always produced by prime factors 2 and 5. If we can count the number of 5s and 2s in n!, our task is done.

How does this work? A trailing 0 is formed by multiplication of 5 and 2. So if we consider all prime factors of all numbers from 1 to n, there would be more 2s than 5s. So the number of 0s is limited by number of 5s. If we count number of 5s in prime factors, we get the result. Consider the following examples:

n = 5: There is one 5 and three 2s in prime factors of 5! (2 * 2 * 2 * 3 * 5). So a count of trailing 0s is min(1, 3) = 1.
n = 11: There are two 5s and eight 2s in prime factors of 11! (2 8 * 34 * 52 * 7). So the count of trailing 0s is min(2, 8) = 2.

We can observe that the number of 2s in prime factors is always more than or equal to the number of 5s. So, if we count 5s in prime factors, we are done.

How to count the total number of 5s in prime factors of n! ?

A simple way is to calculate floor(n/5). For example, 7! has one 5, 10! has two 5s. But, numbers like 25, 125, etc have more than 5 instead of floor (n / 5). For example, if we consider 28! we get one extra 5 and the number of 0s becomes 6. Handling this is simple, first, divide n by 5 and remove all single 5s, then divide by 25 to remove extra 5s, and so on.

Following is the summarized formula for counting trailing 0s:

Trailing 0s in n! = Count of 5s in prime factors of n! = floor(n/5) + floor(n/25) + floor(n/125) + ..

C++
// C++ program to count trailing 0s in n! #include <iostream> using namespace std;  // Function to return trailing 0s in factorial of n int countTrailingZeros(int n) {     // Negative Number Edge Case     if (n < 0)         return -1;      // Initialize result     int count = 0;      // Keep dividing n by powers of     // 5 and update count     for (int i = 5; n / i >= 1; i *= 5)         count += n / i;      return count; }  // Driver Code int main() {     int n = 100;     cout << countTrailingZeros(n);     return 0; } 
C
// C program to count trailing 0s in n! #include <stdio.h>  // Function to return trailing // 0s in factorial of n int countTrailingZeros(int n) {     // Negative Number Edge Case     if (n < 0)         return -1;      // Initialize result     int count = 0;      // Keep dividing n by powers of     // 5 and update count     for (int i = 5; n / i >= 1; i *= 5)         count += n / i;      return count; }  // Driver Code int main() {     int n = 100;     printf("%d\n", countTrailingZeros(n));     return 0; } 
Java
// Java program to count // trailing 0s in n! import java.io.*;  class GFG {     // Function to return trailing     // 0s in factorial of n     static int countTrailingZeros(int n)     {         if (n < 0) // Negative Number Edge Case             return -1;          // Initialize result         int count = 0;          // Keep dividing n by powers         // of 5 and update count         for (int i = 5; n / i >= 1; i *= 5)             count += n / i;          return count;     }      // Driver Code     public static void main(String[] args)     {         int n = 100;         System.out.println(countTrailingZeros(n));     } } 
Python
# Python3 program to count trailing 0s in n!  # Function to return trailing 0s in factorial of n   def countTrailingZeros(n):     # Negative Number Edge Case     if (n < 0):         return -1      # Initialize result     count = 0      # Keep dividing n by     # 5 & update Count     while (n >= 5):         n //= 5         count += n      return count   # Driver program n = 100 print(countTrailingZeros(n)) 
C#
// C# program to count trailing 0s in n! using System;  class GFG {      // Function to return trailing     // 0s in factorial of n     static int countTrailingZeros(int n)     {         if (n < 0) // Negative Number Edge Case             return -1;          // Initialize result         int count = 0;          // Keep dividing n by powers         // of 5 and update count         for (int i = 5; n / i >= 1; i *= 5)             count += n / i;          return count;     }      // Driver Code     public static void Main()     {         int n = 100;         Console.WriteLine(countTrailingZeros(n));     } } 
JavaScript
// JavaScript program to count trailing 0s in n!  // Function to return trailing // 0s in factorial of n function countTrailingZeros(n) {      if (n < 0) // Negative Number Edge Case         return -1;      // Initialize result     let count = 0;      // Keep dividing n by powers of     // 5 and update count     for (let i = 5; Math.floor(n / i) >= 1; i *= 5)         count += Math.floor(n / i);      return count; }  // Driver Code let n = 100; console.log(countTrailingZeros(n)); 

Output
24

Next Article
Find the Factorial of a large number

K

kartik
Improve
Article Tags :
  • Mathematical
  • DSA
  • MakeMyTrip
  • factorial
Practice Tags :
  • MakeMyTrip
  • 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 = 120Input: n = 4Output: 24Explanation
    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 the
    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: 2
    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. Factorial of a numberExamples: Input: 100Output: 933262154439441526816992388562667004- 907159682643816214685929638952175999- 932299156089414639761565182862536979- 2082722375825118521091686400000000
    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 positive integers k and n, where k > 1, find the largest power of k that divides n! (n factorial).Examples: Input: n = 7, k = 2Output: 4Explanation: 7! = 5040, and 24 = 16 is the highest power of 2 that divides 5040.Input: n = 10, k = 9Output: 2Explanation: 10! = 3628800, and 9² = 81 is
    15+ 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) = 1Examples : Input: 5Output: 3Explanation: 5! = 120, i.e., 3 digitsInput: 10Output: 7Explanation: 10! = 3628800, i.e., 7 digits Naive approach
    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