CSES Solutions - Trailing Zeros Last Updated : 02 Apr, 2024 Comments Improve Suggest changes Like Article Like Report Your task is to calculate the number of trailing zeros in the factorial N!. Examples: Input: N = 20Output: 4Explanation: 20! = 2432902008176640000 and it has 4 trailing zeros. Input: N = 6Output: 1Explanation: 6! = 720 and it has 1 trailing zero. Approach: To solve the problem, follow the below idea: If we observe carefully, the number of trailing zeros in N! is same as calculating the number of times the number N! is divisible by 10. We can find this by finding the number of pairs of {2, 5} in the prime factorization of N! as 2 * 5 = 10. Since the number of 2s will always be greater than the number of 5s in prime factorization of N!, therefore we can only calculate the number of 5s to calculate the total number of trailing zeros. Also, the number of 5s in the prime factorization can be different for different numbers. Every multiple of 5 will have at least one 5 in the prime factorization. Similarly, every multiple of 25 will have at least two 5s and every multiple of 125 will have at least three 5s in the prime factorization as so on. So, we can first count the number of 5s for every multiple of 5 then for every multiple of 25, then 125 and so on to calculate the final answer. Step-by-step algorithm: Maintain a function solve(N) to recursively count the number of occurrences of 5 till N.Check if N == 0, then return 0.Otherwise, return N / 5 + solve(N / 5). Below is the implementation of the algorithm: C++ #include <iostream> using namespace std; // Recursive function to calculate the multiples of 5 till N int solve(int N) { if (N == 0) { return 0; } return N / 5 + solve(N / 5); } int main() { int N = 20; cout << solve(N) << "\n"; return 0; } Java import java.util.*; public class Main { // Recursive function to calculate the multiples of 5 till N static int solve(int N) { if (N == 0) { return 0; } return N / 5 + solve(N / 5); } public static void main(String[] args) { int N = 20; System.out.println(solve(N)); } } // This code is contributed by rambabuguphka C# using System; public class GFG { // Recursive function to calculate the multiples of the 5 till N static int Solve(int N) { // Base case: If N is 0 // return 0 if (N == 0) { return 0; } // Recursively calculate the multiples of the 5 and add to the result return N / 5 + Solve(N / 5); } public static void Main(string[] args) { int N = 20; // Call the Solve function and print the result Console.WriteLine(Solve(N)); } } JavaScript // Recursive function to calculate the multiples of 5 till N function solve(N) { if (N === 0) { return 0; } return Math.floor(N / 5) + solve(Math.floor(N / 5)); } function main() { const N = 20; console.log(solve(N)); } main(); Python3 # Recursive function to calculate the multiples of 5 till N def solve(N): if N == 0: return 0 return N // 5 + solve(N // 5) def main(): N = 20 print(solve(N)) if __name__ == "__main__": main() Output4 Time Complexity: O(log5N)Auxiliary Space: O(1) Comment More infoAdvertise with us A alphacozeop Follow Improve Article Tags : Competitive Programming Algorithms-Recursion CSES Problems Similar Reads Complete CP GuideCompetitive Programming - A Complete GuideCompetitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by indust5 min readBasicsDSA TutorialData structures manage how data is stored and accessed, while Algorithms focus on processing this data. Examples of data structures are Array, Linked List, Tree and Heap, and examples of algorithms are Binary Search, Quick Sort and Merge Sort. Why to Learn DSA?Foundation for almost every software li7 min readMaths for DSAMaths is a fundamental component of learning Data Structure and Algorithms, just like in programming. Maths is primarily used to evaluate the effectiveness of different algorithms. However, there are situations when the answer requires some mathematical understanding or the problem has mathematical15+ min readMathematical AlgorithmsThe following is the list of mathematical coding problem ordered topic wise. Please refer Mathematical Algorithms (Difficulty Wise) for the difficulty wise list of problems. GCD and LCM: GCD of Two Numbers LCM of Two Numbers LCM of array GCD of array Basic and Extended Euclidean Steinâs Algorithm fo5 min readBit manipulationBit Manipulation for Competitive ProgrammingBit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usag15+ min readBit Tricks for Competitive ProgrammingIn competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.Bitwise Hacks for Competitive Programming One-Liner Hacks of Bit Manipulation:One-Liner CodeFunctionx&17 min readBitwise Hacks for Competitive ProgrammingPrerequisite: It is recommended to refer Interesting facts about Bitwise Operators How to set a bit in the number 'num': If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ).  First, we left shift '1' to n position via (1<<n)Then, use the 'O14 min readDP for CPDynamic Programming (DP) IntroductionDynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again.The core idea behind DP is to store solutions to subproblems so that each is solved only once. To solve DP problems, we first write a recursive solution in a way t15+ min readDynamic 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 of3 min readDP on Trees for Competitive ProgrammingDynamic Programming (DP) on trees is a powerful algorithmic technique commonly used in competitive programming. It involves solving various tree-related problems by efficiently calculating and storing intermediate results to optimize time complexity. By using the tree structure, DP on trees allows p15+ min readDynamic Programming in Game Theory for Competitive ProgrammingIn the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive e15+ min readAdvancedGraph 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 net3 min readSegment 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 tree3 min readBinary Indexed Tree or Fenwick TreeBinary Indexed Trees are used for problems where we have following types of multiple operations on a fixed sized.Prefix Operation (Sum, Product, XOR, OR, etc). Note that range operations can also be solved using prefix. For example, range sum from index L to R is prefix sum till R (included minus pr15 min readArray Range QueriesThe array range query problem can be defined as follows: Given an array of numbers, the array range query problem is to build a data structure that can efficiently answer queries of a particular type mentioned in terms of an interval of the indices. The specific query can be of type - maximum elemen3 min read Like