Java 整数最大测试,发条模数语句返回不正确的值

Java integer max test with clockwork modulus statement returning incorrect value

在 class 中,我们目前正在使用 "clockwise" 模数函数 - 也就是说,该函数本质上与 Math.floorMod(int a, int b ).

对于class,我不能使用Math.floorMod(),研究题目后写了这个:

 /**
 * Computes {@code a} mod {@code b} as % should have been defined to work.
 *
 * @param a
 *            the number being reduced
 * @param b
 *            the modulus
 * @return the result of a mod b, which satisfies 0 <= {@code mod} < b
 * @requires b > 0
 * @ensures
 * 
 *          <pre>
 * 0 <= mod  and  mod < b  and
 * there exists k: integer (a = k * b + mod)
 *          </pre>
 */
public static int mod(int a, int b) {
    assert b > 0 : "Violation of: b > 0";
    return (((a % b) + b) % b);
}

这是我的问题。这个函数传递了我抛给它的所有情况,除了一个,其中 a = 2 和 b = INTEGER.MAX_VALUE。

应该 return 2,就像 floorMod 一样,但是它 returns 0。无论如何我可以在不使用 floorMod 的情况下解决这个问题吗?

提前致谢。

((a % b) + b)  // this does 2 + INTEGER.MAX and leads to an overflow

您可以使用以下方法来处理此问题并仍然保留 int 值:

public static int mod(int a, int b) {
    assert b > 0 : "Violation of: b > 0";
    return (int) (( (long) (a % b) + b) % b );
}

如果您遵循 Javadoc 中所述的 Math.floorMod 定义,您应该 return a - (floorDiv(a, b) * b)

仅当除法结果为负且 a 不能被 [=16= 整除] 时,

floorDiv(a, b) 给出与 a/b 不同的结果,在这种情况下它 returns a/b - 1(例如floorDiv(-4, 3) == -2,而(-4 / 3) == -1)。

所以如果你根据这个定义实现,你会得到:

public static int mod(int a, int b) {
    assert b > 0 : "Violation of: b > 0";
    int floorDiv = a/b;
    if ((a < 0) && (a % b != 0))
        floorDiv--;
    return a - (floorDiv * b);
}

顺便说一句,这个实现是实际 Math.floorMod 实现的一个子集,它允许两个参数都为负数。