Weird Objective-C Mod Behavior for Negative Numbers

coneybeare picture coneybeare · Jun 13, 2009 · Viewed 32.8k times · Source

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?

Answer

uncleO picture uncleO · Jun 13, 2009
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.