Java中的模数运算

时间:2013-04-30 08:02:35

标签: java math modulo operation

int modx = 101;
int xy = -4/-3;
int answer = xy%modx;
System.out.println("answer= "+answer);

程序会给我答案1,但当我在" PARI GP"中检查答案时答案应该是35。http://en.wikipedia.org/wiki/PARI/GP

我应该怎么做才能在java实现中得到答案?

using Extended Euclidean algorithm, (**3**,101) we get (101*1) + (3*34)
GCD = 1

-4/-3 = 4/3
34*4 = 136
136%101 = 35

这是我能解释的最好的

4 个答案:

答案 0 :(得分:1)

在Java中无法使(-4/-3) mod 101成为35。或者在任何合理的算术系统...... AFAIK。

如果您想要更好的答案,请解释 如何<或者>向我们展示如何让“PARI GP”给你答案。 (我怀疑这里真正发生的是你正在错误地使用“PARI GP”。)


您写道:

  

我只输入-4 / -3%101,答案等于35

事实上,PARA / GP备忘单上写道:

"output previous line, the lines before:    %, %`, %``, etc."

因此,Para GP中的“%”并不意味着模数/余数。基本上,你输入的内容意味着与你认为的意思完全不同的东西。

答案 1 :(得分:1)

根据JLS

The remainder operation for operands that are integers after binary 
numeric promotion (§5.6.2) produces a result value such that 
(a/b)*b+(a%b) is equal to a.

因此,您的表达式xy%modx(1%101)应遵守上述关系,如果您替换为了遵守此关系而使用的值,则(1%101)必须为1

答案 2 :(得分:1)

PARI GP不遵循modular arithmetics惯例。模数只能与整数值一起使用,这就是为什么java会强制转换

-4/-3 to (int) 1

如你所见

1 % 101 = 1

所以java正在给你回复正确答案......

答案 3 :(得分:0)

我认为这源于不了解模数的定义。以一种非数学上非常危险的方式:

模数意味着在你拿走指定数量的全部金额后剩余多少,所以:

1%5
No 5s go into 1 so answer is 1

7%5
1 lot of 5 goes into 7, so 7-1*5=2

16%5
5 lots of 5 go into 16, so 16-3*5=1

这就是模数的工作原理,从中可以清楚地看出:

1.3333%101 
No 101s go into 1.3333, so answer is 1.3333 (or 1 if you let java round to 1 first)