Saturday, December 03, 2005

Christmas Calendar 3/24

Modulus operator (%)

It might be obvious to some, especially those who hva studied maths (and remember the curriculum) that the modulus operator can return negative values.

The modulus operator will return an answer within 0 +- n

For instance: 13 % 10 = 3
but -13 % 10 = -3

This is different from for example ruby's implementation that will return 7 on that same query. try it yourself.

if you want (imho) logical modulus, write your own util-method:
public static int Mod(int i, int n){
return (((i % n) + n) % n)

Thanks to Erlend W. Oftedal for help on this post

No comments: