4

Let us say I have an integer of an arbitrary length such as:

$209484250490600018105614048117055336$

Is there an elegant function which allows me to select the $n$-th digit such that:

$f(1) = 6$ $f(2) = 3$ and so forth.

MITjanitor
  • 2,690

2 Answers2

6

Yes, it can be expressed concisely as $f(n) = \lfloor x \cdot 10^{-n+1} \rfloor \mod{10}$

Dan Brumleve
  • 17,796
3

An alternative:

$f(n)={\large\lfloor} 10\cdot\left(10^{-n}\cdot x-\lfloor 10^{-n}\cdot x\rfloor \right){\large\rfloor}$.

Jonas Meyer
  • 53,602
  • 1
    Iterated floor functions can be simplified, $$f(n)=\lfloor 10^{-n}\cdot x{\large\rfloor}-10\lfloor 10^{-(n+1)}\cdot x{\large\rfloor}$$ – Ethan Splaver Jan 25 '13 at 07:14
  • @Ethan: Thank you. Are you sure it isn't $f(n)=\lfloor 10^{-n+1}\cdot x{\large\rfloor}-10\lfloor 10^{-n}\cdot x{\large\rfloor}$? (Although it would make sense if $f(n)$ corresponded to the coefficient of $10^n$ rather than $10^{n-1}$, I'm using the convention in the question.) – Jonas Meyer Jan 25 '13 at 07:22
  • My bad you are correct, the function I listed corresponds to the nth power of 10, it should be the new one you listed, where you scaled x by a factor of 10. – Ethan Splaver Jan 25 '13 at 07:30
  • @Ethan: Just thought I'd double check that detail, but the idea is clear and gives another, maybe better way to think of it. Thanks again. – Jonas Meyer Jan 25 '13 at 07:32
  • Just a remark: I arrived at my form essentially by thinking of clearing the digits to the left first, then those to the right. Similarly, Ethan's form can be thought of as clearing the digits to the right first, then those to the left. – Jonas Meyer Jan 25 '13 at 17:27