Thursday, February 3, 2011

Multiplication??????

Here is a code to multiply two numbers without using * operator.

    
    while(~scanf("%d%d",&a,&b))
    {
        m=0;
        while(a)
        {
            if(a&1)
                m+=b;
            a>>=1;
            b<<=1;
        }
        printf("%d\n",m);
    }
Thanks to fR0DDY from India for this post.

Detecting a number if it is a power of 2


If(a&-a==a)
Then the number is a power of 2.

It can be proved easily.
Let a=4, then a=00000100 (in 8 bit)
-a is the 2’s complement of a, then, -a=11111100
If we ANDing them then it only produce 1 in the 6th bit and all other is 0. It will be 00000100, that is the number a, and we know 4  it is a power of 2.
But if the number is otherwise, then it can’t results the same number. Because it has more 1 in it’s bit representation, that will be changed in 2’s complement and doesn’t produce the same number while ANDing. Try it yourself J

There is another way to find whether a number is a power of 2 or not. If there is only 1 in a bit representation of a positive number then it is a power of two.
Like,
2= 10
4=100
8=1000
16=10000
See, there is only one 1 in bit representation of this numbers.
We can detect it by this sample code:


#include<bitset>
bitset<16>num;
                               
scanf(“%d”,&num);
ans=num.count();
if(ans==1)
printf("yes");
else 
           printf("no");


I found another process from zobayer vai's blog.
The process is: (just pasting from the post of zobayer vai )


Is a number a power of 2?
How can we check this? of course write a loop and check by repeated division of 2. But with a simple bit-wise operation, this can be done fairly easy.
We, know, the binary representation of p = 2n is a bit string which has only 1 on the nthposition (0 based indexing, right most bit is LSB). And p-1 is a binary number which has 1 on 0 to n-1 th position and all the rest more significant bits are 0. So, by AND-ing p and (p-1) will result 0 in this case:
p   = ....01000 ⇒ 8
p-1 = ....00111 ⇒ 7
-----------------------
AND = ....00000 ⇒ 0

No other number will show this result, like AND-ing 6 and 5 will never be 0.

Detecting a number odd or even


If (x&1==1)
Then x is a odd number. Because every odd number must have a 1 in its last bit.
Like,  3 => 101

so when ANDing with 1, it produce 1 if it odd, else not.