Check if a number is divisible by 3

Viewed 26994

I need to find whether a number is divisible by 3 without using %, / or *. The hint given was to use atoi() function. Any idea how to do it?

16 Answers
bool isDiv3(unsigned int n)
{
    unsigned int n_div_3 =
        n * (unsigned int) 0xaaaaaaab;
    return (n_div_3 < 0x55555556);//<=>n_div_3 <= 0x55555555

/*
because 3 * 0xaaaaaaab == 0x200000001 and
 (uint32_t) 0x200000001 == 1
*/
}

bool isDiv5(unsigned int n)
{
    unsigned int n_div_5 =
        i * (unsigned int) 0xcccccccd;
    return (n_div_5 < 0x33333334);//<=>n_div_5 <= 0x33333333

/*
because 5 * 0xcccccccd == 0x4 0000 0001 and
 (uint32_t) 0x400000001 == 1
*/
}

Following the same rule, to obtain the result of divisibility test by 'n', we can : multiply the number by 0x1 0000 0000 - (1/n)*0xFFFFFFFF compare to (1/n) * 0xFFFFFFFF

The counterpart is that for some values, the test won't be able to return a correct result for all the 32bit numbers you want to test, for example, with divisibility by 7 :

we got 0x100000000- (1/n)*0xFFFFFFFF = 0xDB6DB6DC and 7 * 0xDB6DB6DC = 0x6 0000 0004, We will only test one quarter of the values, but we can certainly avoid that with substractions.

Other examples :

11 * 0xE8BA2E8C = A0000 0004, one quarter of the values

17 * 0xF0F0F0F1 = 10 0000 0000 1 comparing to 0xF0F0F0F Every values !

Etc., we can even test every numbers by combining natural numbers between them.

Related