Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

891233. Factorial Zero Count

Factorial Zero Count

Slug: factorial-zero-count

Difficulty: Easy

Id: 891233

Summary

Given an integer n, find the number of trailing zeros in the factorial of n. For example, for n = 5, the result is 2 because 5! = 120, which has two trailing zeros.

This problem involves basic arithmetic operations and factorial calculations. The key concept is understanding how to calculate the number of trailing zeros in a factorial.

Detailed Explanation

To solve this problem, we need to understand that trailing zeros are formed by pairs of factors of 2 and 5. This means we only need to count the factors of 5 because there will always be more factors of 2 than 5.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable count to store the number of trailing zeros.
  2. Iterate from 2 to n (inclusive). For each iteration:
    • If i is divisible by 5, increment count. This is because every time we encounter a factor of 5, we get a trailing zero.
    • If i is also divisible by 25, increment count again. This is because every time we encounter a factor of 25, we get an additional trailing zero (since there will be more factors of 2 to pair with the 5s).
    • Continue this process until i > n.
  3. Return the value of count.

The time complexity for this solution is O(n), as we need to iterate from 2 to n. The space complexity is O(1), as we only use a constant amount of space.

Optimized Solutions

Java

public int factorialZeroCount(int n) {
    int count = 0;
    for (int i = 5; i <= n; i += 5) {
        while (i % 25 == 0) {
            count++;
            i /= 25;
        }
        while (i % 5 == 0) {
            count++;
            i /= 5;
        }
    }
    return count;
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.