Function to grab specific digits from a number

combinatoricsdecimal-expansion

Recently I’ve been thinking a lot about grabbing digits from numbers, for things like calculating multiplication persistence, i.e. turning $1234$ into a $1\times2\times3\times4$. I’ve been able to come up with $$\lfloor logx \rfloor +1$$ to output the number of digits of the given number $x$, as well as $$\left\lfloor \frac{x}{10^{ \lfloor logx \rfloor -n+1}} \right\rfloor$$ which outputs the first $n$ digits of any number x. But that’s about as far as I’ve been able to think up. Is there any way to construct a function that retrieves the $n^{th}$ digit of a given number? Forgive me if my notation or comprehension is poor, I have no formal education in this field of maths.

Best Answer

If the digit you require is $n$ places from the right (indexed from zero so the units place is at position $0$, the tens place is at $1$ and so forth), then the following function will return the $n$-th digit of the decimal integer $x$:

$\displaystyle f(x, n) = \Big\lfloor \frac x{10^n} \Big\rfloor \pmod{10}$

Example: $f(123456, 3) = 3$.

You can replace $10$ everywhere in the formula with any base $b$ to generalise it.

Related Question