Блог пользователя rootn

Автор rootn, история, 6 лет назад, По-английски

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.

  • Проголосовать: нравится
  • -1
  • Проголосовать: не нравится

»
6 лет назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

AFAIK, this code works faster

rez = a % b;
if (rez < 0)
    rez += b;
»
6 лет назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

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