Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

How to calculate the modulo of negative number in javascript

modulo of the positive number

// num % m
num % m;

πŸ”₯ modulo of a negative number

To achieve the same result in Javascript, you can use a workaround by

  • adding the divisor to the dividend
  • computing the modulo operation.

This will ensure that the dividend is positive and the modulo operation returns a positive result.

// num % m
((num % m) + m) % m;

πŸ”₯ algorithm

const mod = (num % m) => {
    return ((num % m) + m) % m;
}

πŸ“š References