how to calculate (a times b) divided by c only using 32-bit integer types even if a times b would not fit such a type

前端 未结 7 1827
一生所求
一生所求 2021-01-06 00:59

Consider the following as a reference implementation:

/* calculates (a * b) / c */
uint32_t muldiv(uint32_t a, uint32_t b, uint32_t c)
{
    uint64_t x = a;
         


        
7条回答
  •  长发绾君心
    2021-01-06 01:18

    If b = 3000000000 => qn = 3000000000, qn*2 will be overflowed. So I edit the code of Sven Marnach.

    uint32_t muldiv(uint32_t a, uint32_t b, uint32_t c)
    {
    uint32_t q = 0;              // the quotient
    uint32_t r = 0;              // the remainder
    uint32_t qn = b / c;
    uint32_t rn = b % c;
    while (a)
    {
        if (a & 1)
        {
            q += qn;
            if (qn >= UINT32_MAX) {
                cout << "CO CO" << endl;
            }
            r += rn;
            if (r >= c)
            {
                q++;
                r -= c;
            }
        }
        a >>= 1;
        qn <<= 1;
        int temp = rn;
        if (rn > INT32_MAX) {
            // rn times 2: overflow
            rn = UINT32_MAX;// rn 
            temp = (temp - INT32_MAX) * 2; // find the compensator mean: rn * 2  = UINT32_MAX + temp
            qn++;
            rn = rn - c + temp;
        }
        else {
            rn <<= 1;
            if (rn >= c)
            {
                qn++;
                rn -= c;
            }
        }
    
    
    }
    
    //return r;
    return q;
    

    }

提交回复
热议问题