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 1786
一生所求
一生所求 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:10

    If b and c are both constants, you can calculate the result very simply using Egyptian fractions.

    For example. y = a * 4 / 99 can be written as

    y = a / 25 + a / 2475
    

    You can express any fraction as a sum of Egyptian fractions, as explained in answers to Egyptian Fractions in C.

    Having b and c fixed in advance might seem like a bit of a restriction, but this method is a lot simpler than the general case answered by others.

提交回复
热议问题