views:

458

answers:

3

I'm a little freaked out by the results I'm getting when I do modulo arithmetic in Objective-C. -1 % 3 is coming out to be -1, which isn't the right answer: according to my understanding, it should be 2. -2 % 3 is coming out to -2, which also isn't right: it should be 1.

Is there another method I should be using besides the % operator to get the correct result?

+1  A: 

Modulo with negative numbers isn't as straightforward as you might think. See http://mathforum.org/library/drmath/view/52343.html

Spencer Ruport
+3  A: 

Objective-C is a superset of C99 and C99 defines a % b to be negative when a is negative. See also the Wikipedia entry on the Modulo operation and this StackOverflow question.

Something like (a >= 0) ? (a % b) : ((a % b) + b) (which hasn't been tested and probably has unnecessary parentheses) should give you the result you want.

Isaac
A: 

ANSI C99 6.5.5 Multiplicative operators-

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

6.5.5.6: When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded (*90). If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

*90: This is often called "truncation toward zero".

The type of modulo behavior you're thinking of is called "modular arithmetic" or "number theory" style modulo / remainder. Using the modular arithmetic / number theory definition of the modulo operator, it is non-sensical to have a negative result. This is (obviously) not the style of modulo behavior defined and used by C99. There's nothing "wrong" with the C99 way, it's just not what you were expecting. :)

johne