ProgrammingHard

A program uses a modulus of 10^9 + 7 and computes (a - b + MOD) % MOD for a and b in [0, MOD). Why add MOD before the %?

  1. A. To make the result divisible by 2
  2. B. To keep the value non-negative, since a - b can be negative and C's % keeps the dividend's sign
  3. C. To avoid all overflow for any values
  4. D. Because % is undefined for negative numbers in C

Correct answer: B. To keep the value non-negative, since a - b can be negative and C's % keeps the dividend's sign

a - b can be negative, and C99 % then gives a negative remainder. Adding MOD first makes the value non-negative and the % correct.

More C Programming questions

Exams that ask this topic