Modulus operator

Hi Experts,
got a silly question but is driving me crazy.

Why in Java the following statement produce
System.out.println("Mod of -13%64 is: " -13%64) //will print out -13
System.out.println("Mod of 13%64 is: " 13%64) //will print out -13

While in Excel and as well in Python (-13%64) produce 51 and (13%64) produce 13?

Thank you
Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
In Java, the result has the sign of the dividend:

http://en.wikipedia.org/wiki/Modulo_operation
Commented:
System.out.println("Mod of 13%64 is: " 13%64) //will print out -13

this isn't right - it will produce 13.
Author Commented:
@krakatoa
Yes you're right I made a type with copy/paste
Commented:
Actually, it won't even compile, let alone print anything. You probably meant :

System.out.println("Mod of 13%64 is: "+(13%64)) ;//will print out 13

(but when you are done on this question, please don't award any points to me - the other expert's comment is far more determining). thanks.

(Footnote : if you are just concerned with absolute difference, then you can wrap it in Math.abs() of course).
Author Commented:
@CEHI
thanx for the link has been helpful, but the matter is not the sign actually but the different results, now in my case for my sample I solved using Math.floorMod(int x, int y) but I had to install jdk 1.8 becase Jdk 1.7 doesnt have such a method.

Wonder how other people solve that in the previous version
IT Business Systems Analyst / Software DeveloperCommented:
Wonder how other people solve that in the previous version

One way would be to just write a quick utility method...

``````public int mod(int x, int y) {
int result = x % y;
return (result >= 0 ? result : result + y);
}
``````

Interestingly, I just found that BigInteger has separate "mod" and "remainder" operations so you can choose which way you want to go (even in older Java versions), although I don't think this is very nice code, but it should work...

``````int result = BigInteger.valueOf(-13).mod(BigInteger.valueOf(64)).intValue();
``````

Obviously, you could also wrap that in a utility method to make it nicer, but then you may as well just go with the first option which I would also expect to be more efficient.

Experts Exchange Solution brought to you by