-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).
Related
For example,
int result;
result = 125/100;
or
result = 43/100;
Will result always be the floor of the division? What is the defined behavior?
Will result always be the floor of the division? What is the defined behavior?
Not quite. It rounds toward 0, rather than flooring.
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any
fractional part discarded.88) If the quotient a/b is representable, the expression
(a/b)*b + a%b shall equal a.
and the corresponding footnote:
This is often called ‘‘truncation toward zero’’.
Of course two points to note are:
3 The usual arithmetic conversions are performed on the operands.
and:
5 The result of the / operator is the
quotient from the division of the
first operand by the second; the
result of the % operator is the
remainder. In both operations, if the
value of the second operand is zero,
the behavior is undefined.
[Note: Emphasis mine]
Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.
From the ANSI C draft (3.3.5):
If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
So watch out with negative numbers when you are stuck with a C89 compiler.
It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.
Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.
-5 / 2 = -2
5 / 2 = 2
For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).
Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors
Will result always be the floor of the division?
No. The result varies, but variation happens only for negative values.
What is the defined behavior?
To make it clear floor rounds towards negative infinity,while integer division rounds towards zero (truncates)
For positive values they are the same
int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0
For negative value this is different
int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0
I know people have answered your question but in layman terms:
5 / 2 = 2 //since both 5 and 2 are integers and integers division always truncates decimals
5.0 / 2 or 5 / 2.0 or 5.0 /2.0 = 2.5 //here either 5 or 2 or both has decimal hence the quotient you will get will be in decimal.
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.
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.
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.
The other day I decided to write an implementation of radix sort in Java. Radix sort is supposed to be O(k*N) but mine ended up being O(k^2*N) because of the process of breaking down each digit to one number. I broke down each digit by modding (%) the preceding digits out and dividing by ten to eliminate the succeeding digits. I asked my professor if there would be a more efficient way of doing this and he said to use bit operators. Now for my questions: Which method would be the fastest at breaking down each number in Java, 1) Method stated above. 2) Convert number to String and use substrings. 3) Use bit operations.
If 3) then how would that work?
As a hint, try using a radix other than 10, since computers handle binary arithmetic better than decimal.
x >>> n is equivalent to x / 2n
x & (2n - 1) is equivalent to x % 2n
By the way, Java's >> performs sign extension, which is probably not what you want in this case. Use >>> instead.
Radix_sort_(Java)
The line of code that does this;
int key = (a[p] & mask) >> rshift;
is the bit manipulation part.
& is the operator to do a bitwise AND and >> is a right-shift.