Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Objective-C Mod Behavior for Negative Numbers

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?

like image 961
coneybeare Avatar asked Jun 13 '09 04:06

coneybeare


People also ask

Can you do mod with negative numbers?

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.

Can you mod negative numbers in C?

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 ) ).

Are mods always positive?

Is modulus always positive? The answer is “Yes”. Reason: The value of modulus of any number is always positive.

How does mod work with negative numbers Java?

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.


1 Answers

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.

like image 139
uncleO Avatar answered Sep 30 '22 22:09

uncleO