rootn's blog

By rootn, history, 7 years ago, In English

Normally, a % b gives the value of remainder when a is divided by b. Therefore, 5 % 3 should give 2. But what if a is negative, in that case, the answer is multiplied by a negative sign. i.e. -5 % 3 gives -2 as answer. But what is actually is required is a positive answer.

Hence, correctly the mod function can be written as (b + (a % b)) % b.

  • Vote: I like it
  • -1
  • Vote: I do not like it

»
7 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

AFAIK, this code works faster

rez = a % b;
if (rez < 0)
    rez += b;
»
7 years ago, # |
  Vote: I like it +8 Vote: I do not like it

This is good and short, but you may have to watch for overflow if b is large