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
We have a problem of language:
math-er-says: i take this number plus that number mod other-number code-er-hears: I add two numbers and then devide the result by other-number code-er-says: what about negative numbers? math-er-says: WHAT? fields mod other-number don't have a concept of negative numbers? code-er-says: field what? ...
In this case you want the mathematician's mod operator and have the remainder function at your disposal. you can convert the remainder operator into the mathematician's mod operator by checking to see if you fell of the bottom each time you do subtraction.
Not only java script, almost all the languages shows the wrong answer' what coneybeare said is correct, when we have mode'd we have to get remainder Remainder is nothing but which remains after division and it should be a positive integer....
If you check the number line you can understand that
I also face the same issue in VB and and it made me to forcefully add extra check like if the result is a negative we have to add the divisor to the result
UncleO's answer is probably more robust, but if you want to do it on a single line, and you're certain the negative value will not be more negative than a single iteration of the mod (for example if you're only ever subtracting at most the mod value at any time) you can simplify it to a single expression:
int result = (n + 3) % 3;
Since you're doing the mod anyway, adding 3 to the initial value has no effect unless n is negative (but not less than -3) in which case it causes result to be the expected positive modulus.
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.
Why: because that is the way the mod operator is specified in the C-standard (Remember that Objective-C is an extension of C). It confuses most people I know (like me) because it is surprising and you have to remember it.
As to a workaround: I would use uncleo's.
There are two choices for the remainder, and the sign depends on the language. ANSI C chooses the sign of the dividend. I would suspect this is why you see Objective-C doing so also. See the wikipedia entry as well.