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.
Function to grab specific digits from a number?
274 Views Asked by Bumbble Comm https://math.techqa.club/user/bumbble-comm/detail AtThere are 3 best solutions below
On
I do believe I’ve figured it out! It took a bit of thinking and it is a little complicated but consider $$f(x)= \frac{10^{\lfloor logx \rfloor -n+1} \lfloor \frac {x}{10^{\lfloor logx \rfloor -n+1}} \rfloor -10^{\lfloor logx \rfloor -n+2} \lfloor \frac {x}{10^{\lfloor logx \rfloor -n+2}} \rfloor}{10^{\lfloor logx \rfloor -n+1}}$$ Should give back the $n^{th}$ digit of the given number x, from the left side, so it works for irrationals too. Surely this can be much better written or simplified but I’m pretty happy with what I came up with.
On
Illustration by example. Suppose that $n = 12345678$ and you want to retrieve the 6th digit from the left, which is $3$.
$\displaystyle \left\lfloor \frac{n}{10^5}\right\rfloor = 123 = a$
and
$\displaystyle \left\lfloor \frac{n}{10^6}\right\rfloor = 12 = b.$
Then, the desired extraction is $(a - 10b) = 3.$
So, to retrieve the $k$-th digit, where $k$ is not the leftmost digit, you want
$\displaystyle \left\lfloor \frac{n}{10^{(k-1)}}\right\rfloor - \left\{ 10 \times \left\lfloor \frac{n}{10^k}\right\rfloor \right\}.$
If you want the $k$-th digit, which is the leftmost digit, then you want
$\displaystyle \left\lfloor \frac{n}{10^{(k-1)}}\right\rfloor.$
Edit
As indicated in the answer of Deepak, if (for example) $n = 12345678_{\text{base}~9}$, and you want to retrieve the $3$ (or the $1$), you use the same method as before, except that in the denominator(s), $10^{(k-1)}$ and $10^k$ will be replaced by $9^{(k-1)}$ and $9^k$.
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.