简体   繁体   English

如何找到Java的底数和余数?

[英]How to find the floor and remainder of a fraction in Java?

Given integers 'a' and 'b', I would like a method that returns the floor and remainder of a / b such that: 给定整数“ a”和“ b”,我想要一个返回底数和a / b余数的方法,使得:

  • a / b = floor + remainder / |b| a / b =底数+余数/ | b | (where |b| is the absolute value of b), and (其中| b |是b的绝对值),和
  • 0 <= remainder < |b|. 0 <=余数<| b |。

For example, 5/3 = 1 + 2/3. 例如5/3 = 1 + 2/3。

Here's an attempt that works only for positive a and b : 这是仅适用于正数ab的尝试:

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

I need a function that works for all positive and negative numerators and denominators. 我需要一个适用于所有正负分子和分母的函数。 For example, 例如,

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

Implementation 1: Floating Point 实施方案1:浮点数

Uses floating point math to simplify the logic. 使用浮点数学来简化逻辑。 Be warned that this will produce incorrect results for large numbers due to loss of precision. 请注意,由于精度下降,这将对大量产生错误的结果。

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

Implementation 2: Find, then Correct 实施2:找到然后纠正

Finds the floor and remainder using integer division and modulus operators, then corrects for negative fractions. 使用整数除法和模运算符查找底数和余数,然后校正负分数。 This shows that the remainder is relatively difficult to correct without using the floor. 这表明在不使用地板的情况下很难校正剩余部分。

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

Implementation 3: The Best Option 实施方案3:最佳选择

Finds the floor the same way as Implementation 2, then uses the floor to find the remainder like Implementation 1. 以与实施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 };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM