testing value of last digit of an integer.

Karl Hasselström kha at treskal.com
Sun Apr 4 10:27:22 CEST 2004

On 2004-04-03 21:23:08 -0800, David McKen wrote:

> I want to check if the last digit of an integer is 5.
> I am contemplating using the mpz_tstbit function to test for the
> binary representation of 5 which is 0 1 0 1. The leading zero is to
> prevent 13 from accidentally being detected. Any further out and the
> binary digits would not affect the last digit.

This is not true, since ten is not a power of two (I'm assuming that
what you want to know is whether the last digit in the base-ten
representation of your number is five). What you propose is equivalent
to determining whether the last digit of the base-SIXTEEN
representation of the number is five, since base sixteen is what you
get by grouping four binary digits.

> Does anyone know any other way I can do this?

mpz_get_str can compute a base 10 representation of your integer. But
since you only want the last base ten-digit, I suggest you compute the
remainder of your number divided by ten and check if the result is
five (this will be much faster). You'll want to use mpz_tdiv_ui or
something for this.

Karl Hasselström, kha at treskal.com

More information about the gmp-discuss mailing list