So I thought that negative numbers, when mod'ed should be put into positive space... I cant get this to happen in objective-c
I expect this:
-1 % 3 = 2 0 % 3 = 0 1 % 3 = 1 2 % 3 = 2
But get this
-1 % 3 = -1 0 % 3 = 0 1 % 3 = 1 2 % 3 = 2
Why is this and is there a workaround?
When both the divisor and dividend are negative. If both the divisor and dividend are negative, then both truncated division and floored division return the negative remainder.
Anyone can predict the output of a modulus operator when both operands are positive. But when it comes to the negative numbers, different languages give different outputs. In C language, modulus is calculated as, a % n = a – ( n * trunc( a/n ) ).
Is modulus always positive? The answer is “Yes”. Reason: The value of modulus of any number is always positive.
The sign of the first operand decides the sign of the result. x % y always equals x % -y . You can think of the sign of the second operand as being ignored.
result = n % 3; if( result < 0 ) result += 3;
Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With