Monday, 31 July 2017

AND product (hint bit manipulation )

Consider two non-negative long integers, and , where . The bitwise AND of all long integers in the inclusive range between and can be expressed as , where is the bitwise AND operator.
Given pairs of long integers, and , compute and print the bitwise AND of all natural numbers in the inclusive range between and .
Input Format
The first line contains a single integer, , denoting the number of intervals to calculate results for.
Each line of the subsequent lines contains two space-separated long integers describing the respective values of and .
Constraints

Output Format
For each pair of long integers, print the bitwise AND of all numbers in the inclusive range between and on a new line.
Sample Input
3 
12 15 
2 3 
8 13
Sample Output
12 
2 
8
Explanation
There are three pairs to compute results for:
  1. and
    , so we print on a new line.
  2. and
    , so we print on a new line.
  3. and
    , so we print on a new line.
#include <stdio.h>
unsigned long one=1;
int which_msb1(long unsigned int *z,long unsigned int *z1,int flag )
{
    while( ((*z & (one<<63) )== 0 )&&flag>0 )
        {

           (*z)=(*z)<<1;
           (*z1)=(*z1)<<1;
            flag--;
           // printf("flag is %d",flag);
        }
    return flag ;
}
int main() {
    int test ;
    scanf("%d",&test);
    while (test >0){

     unsigned long x;
     unsigned long y;
        scanf("%ld",&x);
        scanf("%ld",&y);
     unsigned int tmp=64;
     //unsigned long prod= x;
     unsigned long z=x;
        unsigned long z1=y;
     int flag=64;
   
      
         //printf("%ld\n",z);
         //printf("%lu/n",z & one<<63);
        flag= which_msb1(&z,&z1,flag);
        //printf("%u\n",flag);
        while (  (z & (one<<63))==(z1 &(one<<63)) &&flag>0 )
        {
            z= z<<1;
            z1=z1<<1;
            flag--;
        }
        //printf("%d",flag);
        int temp2= flag;
        z=x;

        z=z>>(temp2);

        z=z<<(temp2);

        printf("%ld\n",z);

     test--;
 
    }
 return 0;

}

No comments:

Post a Comment