Function to count trailing zeroes

111 Views Asked by At

Recently a friend of mine suggested a question, which was to find the number of trailing zeroes in $(100!)$.

While that should be easy enough to tackle, as I have seen a lot of questions on MSE that deal with exactly this type of problem, I would like to solve a more general problem:

Define a function $f(n)$ using common mathematical operators and other notation that counts the number of trailing zeroes in a given positive integer $n$

Now I have got something in mind, which is: $$f(x)=\sum_{i=1}^{\lfloor log_{10}x\rfloor} \left(1-|sgn(x\mod(10^i)|\right)$$ Where $sgn()$ is the signum function. The function is based on the concept of checking if the number is divisible by successive powers of $10$. Here’s a Desmos link for the function.

While this does seem to work, I would like a more compact function that I can actually work with, while this is something like rewriting a computer algorithm, only using mathematical notation.

All ideas are welcome.

Thanks in advance.

EDIT: As proposed in a comment by @RobertIsrael, another definition for the function is:

$$\min(v_{2}(n), v_{5}(n))$$

with reference to the $p$-adic valuation of $n$.

1

There are 1 best solutions below

4
On

The $f(n)$ you specify as the number of trailing zeroes of $n$ is the highest power of $10$ that divides $n$.

One way to construct such a function uses the following facts:

  • Divisibility of $n$ by $10^k$ can be tested by checking whether $$n = 10^k\left\lfloor\displaystyle\frac{n}{10^k}\right\rfloor \quad\text{or, equivalently, whether}\quad n- 10^k\left\lfloor\displaystyle\frac{n}{10^k}\right\rfloor = 0$$

  • The function $0^{\left|x\right|}$ has the convenient property that the output will be $1$ when $x=0$ and $0$ otherwise. If you prefer, this is an instance of the "Kronecker delta", $\delta_{x0}$.

$$0^{\left|x\right|} \, =\, \delta_{x0} \, =\, \begin{cases} 1 &\text{ if }x=0 \\ 0 &\text{ if }x \neq 0 \end{cases}$$

These two facts together allow us to express $f(n)$ as a sum as follows:

$$f(n) = \displaystyle\sum\limits_{k=1}^{\left\lfloor\log_{10}n\right\rfloor} \, 0^{\,\left|\,n-10^k\left\lfloor\displaystyle\frac{n}{10^k}\right\rfloor\,\right|}$$

Each summand will add $1$ to the total, until $10^k$ no longer divides $n$, at which point any remaining summands will add $0$. In this way, the function counts the number of trailing zeroes of $n$.

This is a fun expression, but it isn't very practically useful.