[英]How can I handle non-negative mods?
When I use the operator % in my Java programs, I keep getting negative answers. 当我在Java程序中使用运算符%时,我不断得到否定答案。 Example: -1%100 gives -1. 示例:-1%100给出-1。 While this is mathematically correct, I want to get the normal mathematical solution, or 99. In other words, I want to get the smallest positive integer solution. 虽然这在数学上是正确的,但我想得到正常的数学解,或99.换句话说,我想得到最小的正整数解。 Is there any simple solution for this in Java (perhaps something I overlooked in Math? -- I can't find it)? 在Java中是否有任何简单的解决方案(也许我在数学中忽略了什么? - 我找不到它)?
I also want to clarify that if there is something in the API that does this, a link would be awesome. 我还想澄清一下,如果API中有一些东西可以做到这一点,那么链接就会很棒。
You can just do this? 你可以这样做吗?
int d = 100;
int x = -1 % d;
if (x < 0)
x += d;
This should work for any positive d
. 这适用于任何积极的d
。
You can do the following 您可以执行以下操作
int myMod(int x, int modulo)
{
return ((x % modulo) + modulo) % modulo
}
This works, for any values in place of d or x. 这适用于代替d或x的任何值。
int d=100;
int x=-1%d;
while (x<0)
x+=d;
i < 0 ? n - ((-i - 1) % n + 1) : i % n
For example: 例如:
class Mod {
public static int mod(int i, int n) {
return i < 0 ? n - ((-i - 1) % n + 1) : i % n;
}
public static void main(String [] args) {
System.out.println("mod(-201, 100) == " + mod(-201, 100));
System.out.println("mod(-200, 100) == " + mod(-200, 100));
System.out.println("mod(17, 100) == " + mod(17, 100));
System.out.println("mod(100, 100) == " + mod(100, 100));
}
}
And 和
$ javac Mod.java && java Mod
mod(-201, 100) == 99
mod(-200, 100) == 0
mod(17, 100) == 17
mod(100, 100) == 0
No loops. 没有循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.