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.
AFAIK, this code works faster
This is good and short, but you may have to watch for overflow if b is large