Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Chk divisibility of # by 4 2

Status
Not open for further replies.

manvid

Programmer
Apr 1, 2002
37
IN
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?

-vs
 
Try
Code:
#include <stdio.h>
int main ( ) {
    int i;
    for ( i = -10 ; i < 10 ; i++ ) {
        printf( &quot;%d %d %d\n&quot;, i, (i & (~3)) == i, (i & 3) == 0 );
    }
    return 0;
}
 
Hello Salem,
Can you please give the algorith or logic behind this solution of yours. Thanks
 
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.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top