How can 1 check whether a given number is divisible by 4 using bitwise operations.. The catch here is no loops shud b employed.
It is obvious that a # divisible by 4 (starting from 4 onwards) has one 1 bit on.
But how can this be checked without using loops?
#include <stdio.h>
int main ( ) {
int i;
for ( i = -10 ; i < 10 ; i++ ) {
printf( "%d %d %d\n", i, (i & (~3)) == i, (i & 3) == 0 );
}
return 0;
}
If a number is divisible by 4, the 2 lowest bits are not set therefore (number & 3) should be 0.
Similarly, if it is divisible by 2, the lowest bit is not set ((number & 1) == 0) and if it is divisible by 8, the 3 lowest bits are not set ((number & 7) == 0) etc.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.