简体   繁体   中英

multiply two numbers using only bit operations

While learning Bit operations in c,I was searching for code to multiply two numbers using only bit operations , I found the following code!. I am unable to understand how ternary operator is working in the following scenario and producing the correct o/p.

#include<stdio.h>
static int multiply (int x, int y) 
{
    return  y==0?0:((y&1) ==1?x:0)+multiply(x<<1,y>>1);
}
int main()
{
    printf("%d",multiply(2,3));
    return 0;
}

Can someone please explain how is the above code working?.

That is not using "only bit operations", since it's using + to add numbers.

Maybe indenting can help break up the complicated expression:

return (y == 0 ? 0
               : (y & 1) == 1 ? x
                              : 0)
       + multiply(x << 1, y >> 1);

Basically it's a recursive addition, that stops when y reaches 0. If the least significant bit of y is set, x is added to the result, else it is not. On each recursion, one bit of y is dropped so that it eventually will reach 0. The value of x is shifted to the left, very much like when doing multiplication by hand.

For instance if x = 3 (binary 11 ) and y = 6 (binary 110 ), it will compute

0 * 3 + 1 * 6 + 1 * 12 = 18

And of course 18 is 3 * 6.

Each recursion step is written as a * b where a is the least significant bit of y at that step (reading from the left, you get 0, 1, 1 which is the bits of y starting with the least significant bit) and b is the value of x at that step.

If y is odd, x * y = x + (x * 2) * (y / 2)

If y is even, x * y = (x * 2) * (y / 2)

With the logic above, and use recursion until y = 0 .

If you are struggling understanding a complex nested use of the conditional operator, then simply expand it to an if statement:

static int multiply (int x, int y) 
{
    if (y==0)
        return 0;
    else
        return ((y&1) ==1?x:0)+multiply(x<<1,y>>1);
}

And then expand the inner conditional operator:

static int multiply (int x, int y) 
{
    if (y == 0)
        return 0;
    else if ((y&1) == 1)
        return x + multiply(x<<1, y>>1);
    else return
        return multiply(x<<1, y>>1);
}

Once you've expanded it like this, it should be clear what the expression is doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM