# A newbie question

Torbjorn Granlund tg at gmplib.org
Mon Aug 17 17:05:34 CEST 2009

```"Bird, John" <John.Bird at ca.com> writes:

I'm looking through the manual for a function that pulls out the Xth
digit of an int.

So something like this:
unsigned long uslong;
mpz_set_str(n, "111111111111111911111", 10);
uslong = mpz_get_index_ui(n, 5);

uslong would now equal 9

The closest thing in the manual I can find is mpz_getlimbn. Is this the
function I am looking for? If so, can anyone suggest an efficient way of
calculating an "index" from that?

To get the kth decimal digit, either

1. Compute t = n div 10^{k-1} then get the digit by computing t mod 10.
2. Compute r = n mod 10^k, the get the digit as r div 10^{k-1}.
(Compute 10^{k-1} first and save it, then compute 10^k from 10^{k-1}
with a multiplication by 10.)

The operation div is truncating integer division.

This method is not optimal, but it is the only method that is simple to
implement using mpz.  An better method would compute a one-word
approximation p to 10^{k-1} and compute n div p, checking if this is
close to an integer, and if it is, compute a gradually better
approximation to 10^{k-1} until one can tell things are safe.

--
Torbjörn
```