4

I would like to construct a function thats output is equal to the number of digits used to represent the number given as an input.

For example:
$f(5) = 1$
$f(9) = 1$
$f(13) = 2$
$f(99) = 2$
$f(682) = 3$
$f(999) = 3$
$f(9999)= 4$
etc.

Is it even possible with one function and if not, why not?
Can anyone help me with this or at least point me in the right direction?

amWhy
  • 209,954
logicbird
  • 255

1 Answers1

14

The function is for integers in $\mathbb{Z}$

$D_{10}(n)=\lfloor \log_{10}|n| \rfloor+1$

if $n \neq 0$ and $D_{10}(0):=1$. You can leave the absolute function away if you just want to look at positive integers.

Note that for any base you want you could use

$D_{b}(n)=\lfloor \log_{b}|n| \rfloor+1$

for digits in base b, this is quite nice.

You have to use floor because especially $D_{10}(10)=2$. $\log_{10}n$ is the logarithm to base 10.

Listing
  • 13,937