/home/huy/cdn-cgi

cdn-cgi: Development Log

01.21.2022 - Math/Count number of digits with Logarithm

Suppose that a number $n$ has $d$ digits, then:

$$ 10^{d-1} \leq n \lt 10^{d} $$

Because $10^d$ is the smallest integer with $d + 1$ digits.

Now, take logs base 10 of this relation:

$$ log_{10}{(10^{d-1})} \leq log_{10}{n} \lt log_{10}{(10^d)} $$

This becomes:

$$ d-1 \leq log_{10}{n} \lt d $$

If you now take the integer part of $log_{10}{n}$, throwing away everything to the right of the decimal point, you will get $\lfloor log_{10}{n} \rfloor = d-1$. Thus, $d = \lfloor log_{10}{n} \rfloor + 1$.

For example, $234$ is a $3$ digits number, take the logs base 10:

$$ log_{10}{(234)} \approx 2.369215 $$

If we take the integer part and throw away everything to the right of the decimal point, it's $2$.

The calculation can be done programmatically like this:

#include <math>

int digits = log10(n) + 1;

Source: Proof: How many digits does a number have? - StackExchange Mathematics

Read more