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

标签 java math int modulus

在类里面,我们目前正在使用“顺时针”模函数 - 也就是说,该函数本质上与 Math.floorMod(int a, int b) 的工作方式相同。

对于类,我不能使用 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 的情况除外。

应该返回 2,就像 FloorMod 所做的那样,但它返回 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 );
}

关于Java整数最大值测试与发条模数语句返回不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707213/

相关文章:

java - Citrus 框架 - 无法成功构建示例

java - 优化索引 lucene 5.2.1

c# - 更快的 Log2Ceil

c++ - 从 int 转换为 bool 时出错

python - 我如何在 python 中将 int16 打包成字节

java - android:如何将字符串转换为日期

java线程: Unusual behaviour of threads

c - 如何计算递增变量的总计

math - std::erf 的精度是多少?

c - 在纯 c 中查找字符串 (char*) 中的 int