testing value of last digit of an integer.

Joachim Durchholz jo at durchholz.org
Sun Apr 4 11:51:17 CEST 2004


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.

You'd still get false negatives. For example, 25 is 11001.

Your algorithm will have to look at all the bits in the representation.
Reason:
Setting or clearing any bit in the number will increase resp. decrease 
the number by a power of two. E.g. flipping bit 10 will change the value 
by +/- 1024; if the number previously happened to have a final decimal 
digit of 1 resp. 9, the result will end with a 5.

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

Take the number mod 10 and check whether the result is 5.
The test should be
   mpz_cdiv_ui (n, 10L) == 5L
(take this with a spoonful of salt, I haven't used GMP directly yet, 
just reading the docs).

The modulo-10 operation should already be very fast. It's a central 
operation when it comes to converting a GMP integer to human-readable 
form, so it's quite likely that it got special attention from the 
optimization folks.

Regards,
Jo


More information about the gmp-discuss mailing list