java Java模块化划分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7860795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:44:48  来源:igfitidea点击:

Java modular division

javadivisionmodular-arithmetic

提问by Tony

I'm doing some error correcting, and I need to divide two digits under mod 11 in Java.

我正在做一些纠错,我需要在 Java 中的 mod 11 下除以两位数。

Now this I know, from using a modular calculator:

现在我知道了,通过使用模块化计算器:

9/1 mod 11 = 9
2/10 mod 11 = 9

The problem comes in getting Java to calculate this. In Java:

问题在于让 Java 来计算这个。在 Java 中:

(9 / 1) % 11 = 9 - This is fine
(2 / 10) % 11 = 0 - This is not correct.

I know that Java cannot technically perform modular operations, and part of me is thinking that I either need to somehow calculate the inverse, or use an array to store the possible output values.

我知道 Java 在技术上不能执行模块化操作,我的一部分在想我要么需要以某种方式计算逆,要么使用数组来存储可能的输出值。

回答by Luke Woodward

I think what you are looking for is how to find the multiplicative inverse of a number modulo 11.

我认为您正在寻找的是如何找到数字模 11 的乘法倒数。

10 is its own inverse modulo 11, so it isn't a particularly useful example. Instead, let's find the multiplicative inverse of 7 modulo 11.

10 是它自己的逆模 11,所以它不是一个特别有用的例子。相反,让我们找到 7 模 11 的乘法倒数。

To do this, we solve the equation 7a + 11b = 1 for a and b in integers. We use the Euclidean algorithmto find suitable values for a and b. In this case, we can take a = -3 and b = 2. We ignore the value of b, and take a ( = -3) to be the inverse of 7 modulo 11. In modulo-11 arithmetic, 7 times -3 is 1.

为此,我们对 a 和 b 以整数形式求解方程 7a + 11b = 1。我们使用欧几里得算法为 a 和 b 找到合适的值。在这种情况下,我们可以取 a = -3 和 b = 2。我们忽略 b 的值,取 a ( = -3) 为 7 模 11 的倒数。在模 11 算术中,7 乘以 -3是 1。

If we don't like negative numbers, we can take the inverse of 7 modulo 11 to be 8 ( = -3 + 11) instead.

如果我们不喜欢负数,我们可以取 7 模 11 的倒数为 8 (= -3 + 11)。

So, instead of dividing by 7 modulo 11, we multiply by -3, or by 8. For example, in modulo-11 arithmetic, 9 / 7 = 9 * 8 = 72 = 6.

因此,我们不是除以 7 模 11,而是乘以 -3 或乘以 8。例如,在模 11 算术中,9 / 7 = 9 * 8 = 72 = 6。

If you only ever have one modulus to work with (e.g. you only ever work modulo 11), it's probably better to calculate a table of multiplicative inverses modulo 11 beforehand and use that in your calculations.

如果您只有一个模数可以使用(例如,您只使用模 11),那么最好事先计算一个乘法逆模 11 的表格并在您的计算中使用它。

回答by óscar López

Not sure if this is what you intend, but...

不确定这是否是您的意图,但是...

public static int divmod(int dividend, int divisor, int mod) {
    if (dividend >= divisor)
        return (dividend / divisor) % mod;
    return mod - dividend;
}

Testing it:

测试它:

divmod(9, 1, 11)  // returns 9
divmod(2, 10, 11) // returns 9