How to use the remainder operator - java

Currently I am working with the % operator in Java. I thought I understood it but after coming across this question am now confused. So I know that 10 % 3 = Remainder 1. My question is why would 3 % 8 = Remainder 3 I thought that this would instead equal 0 because 3 goes into 8 zero times? Another example would be 2 % 8 = Remainder 2 why would this ones remainder not be zero also? If someone could explain why this is that would be awesome! Thank you!

The remainder operator is explained in the Java tutorial at https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
If you are looking for a modulo operator, then use Math.floorMod at it treats negative numbers as you'd expect. The documentation gives examples of the difference between % and floorMod: http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int-

This is the correct behavior, mathematically speaking.
Hopefully people will indulge me a digression, but the integers mod n are all of the integers from 0 to n - 1. They form a multiplicative group that's important to number theory and cryptography. In fact, if you do
for (int i = 0; i < x; i++) {
Console.WriteLine(i % n);
}
this will give you all the numbers from 0 to (n - 1) over and over again, just like the group.
Without going into details, a mathematical group is a set with an operation that behaves more or less like you'd expect it to with "ordinary" arithmetic. For example, if a set forms a group under multiplication, that means that multiplication "works" for that set.
If n is the power of a prime (e.g. 32), then the integers mod n form a finite field, meaning that it behaves quite a bit like ordinary arithmetic.
TL;DR This behavior is by design. It's actually mathematically perfectly correct as well.

Related

Can someone explain how reversing an integer using % 10 works?

To reverse an integer and put it into a list, one would do the following (where x is some integer):
int lastDigit = x;
while(lastDigit != 0)
{
list.add(lastDigit % 10);
lastDigit /= 10;
}
So if x was 502, 2 0 and 5 would get added to the list.
This is obviously really useful, but until yesterday I thought the only way to do something like this was by converting the int to a string first.
I'm not sure if this is just common knowledge but I had not seen this method before today. I would like to understand how it works instead of merely memorizing it.
Could someone explain why the number modulus 10 gives the last digit, and why dividing it by 10 gives the next digit on the next iteration? Why would it eventually equal 0?
The modulus operator gives you the remainder from doing a division calculation.
502 % 10 is 2 because 502/10 = 50 plus a remainder of 2.
Therefore the remainder in this calculation is 2, meaning 2 will be added to the list.
The division by ten in the next line is performed using integer arithmetic, so 502/10 gives a result of 50.
Any non-negative number less than 10 will give a result of zero, ending the loop.
Think of % 10 as getting the least significant (right most) digit in decimal system (hence 10).
And then think of / 10 as shifting all digits one place right (also decimal). You obviously have to do it until the number is 0. All remaining digits can be understood as leading zeros in this case.
In binary system you can also use the bitwise operations & 1 and >> 1 instead of modulo (% 2) and integer (/ 2) divisions.
The list append operation (here add) is the one that reverses the order. The operations above are just for extraction of the single digits.

Modulus operator incorrect for negative numbers

I am having a problem with the Java modulus function.
For some reason the computer has -3 % 26 equal to -3 when it should equal 23, since the lowest multiple of 26 less than -3 is -26 and -3 - -26 is 23.
Also, if you add 26 to -3, which is essentially adding a modulus of 0, then the result should not change, and the result should become 23. Can anyone explain why Java has -3 % 26 == -3 and not 23 and how to fix this problem?
In the modulus logic the resulting values should be the remainder to get to 0. So when you say -3%26, the result is -3 as to add 3 to get to 0.
Mathematicians usually define the remainder when the integer a is divided by the positive integer b to be a - bq, where the quotient q is floor(a ÷ b). According to this definition, the remainder when -3 is divided by 26 is 23 as you rightly say.
However, the Java programming language defines remainder differently. Instead of using floor (i.e. rounding towards negative infinity), the rounding is done towards zero. This doesn't change the answer for positive values, but for negative a and positive b the Java answer is b smaller than the mathematicians' answer (unless b divides exactly into a, in which case everyone agrees the answer is 0). Therefore -3 % 26 == 23 - 26 == -3.
Java programmers usually call % the remainder operator, but you are correct that it is also commonly called the modulus operator. In Visual Basic it's even written Mod, but it works the same as % in C / C# / Java etc.
In my opinion, rounding towards zero rather than negative infinity is a mistake and it only makes life harder. For example, to test if an integer n is odd you ought to be able to do if (n % 2 == 1), but that doesn't work because if n is negative and odd the answer is -1. I don't know which language did it first, but the same mistake has been repeated by C, C++, C# and Java. Languages that do integer division correctly (in my view) include Python, Ruby and Haskell.
In Java 8, methods have been added to the Math class for division where the rounding is towards negative infinity rather than zero. The methods are.
Math.floorDiv(int, int)
Math.floorMod(int, int)
Math.floorDiv(long, long)
Math.floorMod(long, long)
Math.floorMod(-3, 26) returns 23 as you wanted.

Modulo not showing right value

-46 modulo 7 is 3, but I get -4. Why?
int sa=-46;
int p=7;
System.out.println(sa);//-46
sa=sa%p;
System.out.println(sa);//-4
Edit:
This is how I solved it
(sa) % p + p) % p;
Java definition of % (remainder operator)
The Java programming language provides operators that perform
addition, subtraction, multiplication, and division. There's a good
chance you'll recognize them by their counterparts in basic
mathematics. The only symbol that might look new to you is "%", which
divides one operand by another and returns the remainder as its
result.
(see source of reference here)
If you want to create a modulo function that returns only numbers in the range [0, n) when you ask for modulo n you will have to write it (simple).

bit complement operator in euclidean division

https://math.stackexchange.com/questions/679146/euclidean-divison-program
did not answer this query.
I learnt that, Given two integers a and b, with b ≠ 0, there exist unique integers q and r such that a = bq + r and 0 ≤ r < |b|, where |b| denotes the absolute value of b - Definition euclidean division
Corresponding program that implements this logic is as shown below:
int ifloordiv(int n, int d){
if (n >= 0)
return n / d;
else
return ~(~n / d);
}
After reading the above code, It look obvious for me to understand if(n>=0){} block code logic that we are doing real division not euclidean.
But, else{(n<0)} code logic using bit complement operator(~) was not looking obvious to me to understand the thinking approach behind usage of ~ operator. Generally we use >> operator when we think of division.
I know that java ~ operator is 1's complement operator on integral types.
My question is:
I would like to understand the thinking approach on, How can i think of using bit complement operator(~) that it helps you to perform euclidean divison when n<0. Because it was not obvious for me to think on using ~ operator. Please help me tune my approach.
~n is -n - 1.
So ~(~n / d) is -((-n - 1) / d) - 1.
For negative values of n and positive values of d, this turns out to be division that rounds down (division normally rounds towards zero, so up for negative values of n). I can't explain why that is.

Modular Math in Java (Number Line which Wraps Around)

I am trying to create a simple function that utilizes modular arithmetic. This is essentially a number line that wraps around. Specifically I want to use a Mod 8 number line in Java.
What I want is to compare two numbers between 0 and 7. I want to subtract these numbers to get a difference score. However, instead of 0-7=-7, I want it to equal 1. The idea being that after you reach 7, the number line wraps around back to 0 (therefore 0 and 7 are only one space across.)
Are there any packages that fit this criterion?
how about ((0-7)+8) % 8 ? This should fix up your case.
Note: % is the Modular operator.
It appears you want to reverse what negative numbers do with modulos. Keep in mind that the modulus is the remainder after integer division. Normally you would have a range that looks like this:
-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
You want it to look like this for the same series of values:
1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
If you want to solve for the general case where you can have any negative number (such that it will work for -15, -20, -27 as well as -7) then you have to adjust it after the modulus, like this:
int m = x % 8;
m = (m < 0) ? m + 8 : m;
Essentially this leaves the positive case alone, and will adjust the negative case so the numbers roll over as you want them to.
An alternative way to do this with straight math is to take the modulus twice:
int m = ((x % 8) + 8) % 8
The first modulus gives you your expected range from -7 to 7. The addition adjusts the negative modulus so that it is positive, but of course moves the positive values above 7. The second modulus ensures that all the answers are in the range 0 to 7. This should work for any negative number as well as any positive number.
It sounds like you need to use the % modulo operator. Perhaps write a set of integer functions which work with modulo math, eg. Modulo plus would be =(a+b) % 8;
The modulo operation is what you want. However, the % operator in Java, which is often called modulo, isn't the mathematical modulo. It's rather the remainder operator. The difference is subtle and often irrelevant. It's only important if you have negative parameters like in your case. I think Wikipedia can explain the exact difference.
For you're "wrap around" you need the mathematical version of modulo which sadly isn't implemented in Java for Integer. However, the BigInteger class has a mod() function which does exactly what you need:
BigInteger.valueOf(0-7).mod(BigInteger.valueOf(8)).longValue()
It's not pretty but works.
Um... there is the built-in modulus operator %, which is also present in basically every other language that's at all popular these days.

Categories