Editorial for DMOPC '16 Contest 2 P4 - Zeros


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: jimgao

Knowledge required: number theory, binary search

First of all, it is important to recognize the relationship between N! and its number of trailing zeros. A zero is formed with a pair of a factor of 2 and a factor of 5. In fact, it is not necessary to account for the count of both, since the number of zeros is dependent on the lesser of the two, and the number of 5 will always be less or equal than that of 2s.

To solve for the 50% subtask, we can simply brute-force the value of N such that N! will have a number of trailing zeros in the range of [a,b].

Time Complexity: \mathcal{O}(b)

To solve for the rest of the cases, it is important to recognize that the number of trailing zeros of N! will always be non-decreasing in relationship to an increasing N. Hence, we can use binary search to find:

  1. The minimum N such that N! has at least a trailing zeros.
  2. The maximum N such that N! does not have more than b trailing zeros.

The number of valid values of N can be calculated by subtracting the two and adding one.

Time Complexity: \mathcal{O}(\log_2 \max(b))


Comments

There are no comments at the moment.