整数乘以有理数,没有中间溢出

Multiplying integer by rational without intermediate overflow

本文关键字:中间 溢出 有理数 整数      更新时间:2023-10-16

我有一个表示非负有理数p/q的结构体:

struct rational {
    uint64_t p;
    uint64_t q; // invariant: always > 0
};

我想用我的有理数乘以一个uint64 n,得到一个整数结果,四舍五入。也就是说,我要计算:

uint64_t m = (n * r.p)/r.q;

同时避免n * r.p的中间溢出。(当然,最终结果可能溢出,这是可以接受的。)

我该怎么做?有没有一种不用高乘法的方法?

(我查看了boost::rational,但它似乎没有提供此功能)

你可以使用农民乘法:

// requires 0 < c < 2^63
// returns (a * b) / c.
uint64_t multDiv(uint64_t a, uint64_t b, uint64_t c) {
  uint64_t rem = 0;
  uint64_t res = (a / c) * b;
  a = a % c;
  // invariant: a_orig * b_orig = (res * c + rem) + a * b
  // a < c, rem < c.
  while (b != 0) {
    if (b & 1) {
      rem += a;
      if (rem >= c) {
        rem -= c;
        res++;
      }
    }
    b /= 2;
    a *= 2;
    if (a >= c) {
      a -= c;
      res += b;
    }
  }
  return res;
}

要么128位,要么使用Karatsuba乘法;或者你可以用中国的余数定理来表示(n * r.p)模p1和模p2。