On 4/9/2011 2:02 PM, Willem wrote:

> dr.oktopus wrote:

> ) Ok, today I seems to be a little dumb.

> ) What I have to do is to make mod operator (m % n) work even

> ) if m is a negative number.

>

> % is the remainder operator, not the mod operator.

> However, observe that the result is still equivalent within

> the given modulus.

>

> Therefore, this should work:

>

> r = m % n;

> if (r< 0) r += n;
Observe that `n' is `unsigned', so `m % n' is equivalent

to `(unsigned)m + n', which for negative `m' is equivalent to

(in mathematical notation now) `(UINT_MAX + 1 + m) % n', which

means the expression is wrong unless `n' divides UINT_MAX+1,

that is, unless `n' is an integral power of 2.

For example, with `m == -1' `n == 5u', `UINT_MAX=65535',

this formula produces the answer 0, while the O.P. wanted 4.

> Or if you want a single expression:

>

> r = ((m % n) + n) % n;
Same problem.

--

Eric Sosman

(E-Mail Removed)d