如何在Java中找到分数的下限和余数?

dln*_*385 2 java math methods function

给定整数 'a' 和 'b',我想要一个返回 a / b 的下限和余数的方法,这样:

  • a / b = 下限 + 余数 / |b| (其中 |b| 是 b 的绝对值),并且
  • 0 <= 余数 < |b|。

例如,5/3 = 1 + 2/3。

a这是仅适用于 正和的尝试b

public static long[] floorAndRemainder(long a, long b) {
  long floor = a / b;
  long remainder = a % b;
  return new long[] { floor, remainder };
}
Run Code Online (Sandbox Code Playgroud)

我需要一个适用于所有正负分子和分母的函数。例如,

  • -5/3 = -2 + 1/3
  • 5/-3 = -2 + 1/3
  • -5/-3 = 1 + 2/3

dln*_*385 5

实现1:浮点

使用浮点数学来简化逻辑。请注意,由于精度损失,这会导致大量数据产生不正确的结果。

public static long[] floorAndRemainder(long a, long b) {
  long floor = (long) Math.floor(a / (double) b);
  long remainder = Math.abs(a - floor * b);
  return new long[] { floor, remainder };
}
Run Code Online (Sandbox Code Playgroud)

实施 2:查找,然后纠正

使用整数除法和模运算符求取下限和余数,然后纠正负分数。这表明在不使用地板的情况下,余数是相对难以纠正的。

public static long[] floorAndRemainder(long a, long b) {
  long floor = a / b;
  long remainder = a % b;
  boolean isNegative = a < 0 ^ b < 0;
  boolean hasRemainder = remainder != 0;

  // Correct the floor.
  if (isNegative && hasRemainder) {
    floor--;
  }

  // Correct the remainder.
  if (hasRemainder) {
    if (isNegative) {
      if (a < 0) { // then remainder < 0 and b > 0
        remainder += b;
      } else { // then remainder > 0 and b < 0
        remainder = -remainder - b;
      }
    } else {
      if (remainder < 0) {
        remainder = -remainder;
      }
    }
  }
  return new long[] { floor, remainder };
}
Run Code Online (Sandbox Code Playgroud)

实施3:最佳选择

以与实现 2 相同的方式查找下限,然后像实现 1 一样使用该下限查找余数。

public static long[] floorAndRemainder(long a, long b) {
  long floor = a / b;
  if ((a < 0 ^ b < 0) && a % b != 0) {
    floor--;
  }
  long remainder = Math.abs(a - floor * b);
  return new long[] { floor, remainder };
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么使用“^”而不是“!=”? (2认同)