How can I perform multiplication without the '*' operator?

前端 未结 30 1589
别跟我提以往
别跟我提以往 2020-12-01 01:47

I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it\'s like this

<
30条回答
  •  天涯浪人
    2020-12-01 02:46

    One evening, I found that I was extremely bored, and cooked this up:

    #include 
    
    typedef unsigned int uint32;
    
    uint32 add(uint32 a, uint32 b) {
        do {
            uint32 s = a ^ b;
            uint32 c = a & b;
            a = s;
            b = c << 1;
        } while (a & b)
        return (a | b)
    }
    
    uint32 mul(uint32 a, uint32 b) {
        uint32 total = 0;
        do {
            uint32 s1 = a & (-(b & 1))
            b >>= 1; a <<= 1;
            total = add(s1, total)
        } while (b)
        return total;
    }
    
    int main(void) {
        using namespace std;
        uint32 a, b;
    
        cout << "Enter two numbers to be multiplied: ";
        cin >> a >> b;
    
        cout << "Total: " << mul(a,b) << endl;
        return 0;
    }
    

    The code above should be quite self-explanatory, as I tried to keep it as simple as possible. It should work, more or less, the way a CPU might perform these operations. The only bug I'm aware of is that a is not permitted to be greater than 32,767 and b is not permitted to be large enough to overflow a (that is, multiply overflow is not handled, so 64-bit results are not possible). It should even work with negative numbers, provided the inputs are appropriately reinterpret_cast<>.

提交回复
热议问题