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 1854
一生所求
一生所求 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:08

    I suppose there are reasons you can't do

    x = a/c;
    x = x*b;
    

    are there? And maybe add

    y = b/c;
    y = y*a;
    
    if ( x != y )
        return ERROR_VALUE;
    

    Note that, since you're using integer division, a*b/c and a/c*b might lead to different values if c is bigger than a or b. Also, if both a and b are smaller than c it won't work.

提交回复
热议问题