【问题标题】:How to find the floor and remainder of a fraction in Java?如何在Java中找到分数的底和余数?
【发布时间】:2015-01-17 15:25:35
【问题描述】:

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

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

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

这是一个仅适用于正面ab 的尝试:

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

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

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

【问题讨论】:

    标签: java function math methods


    【解决方案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 };
    }
    

    实现 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 };
    }
    

    实施 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 };
    }
    

    【讨论】:

    • 为什么使用^ 而不是!=
    • @Maria 个人喜好。对于 XOR,它是一个完全有效的布尔运算符,所以我不明白为什么不这样做。另外,如果xyz 是布尔表达式,那么我发现x ^ y ^ zx != y != z 更具可读性。
    • 我不是在批评,我是在问,因为我以前从未见过它使用过,我想知道是否有性能优势,或者选择其中一个的具体原因。跨度>
    猜你喜欢
    • 2014-12-06
    • 2011-10-23
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多