0

I am a thirteen-year-old who is learning programming. I know Javascript and Python pretty well, but I mostly program Javascript using Node.js as my compiler.

I have a pretty naïve question. I am writing an implementation of a circular buffer, and I need to know the remainder when -7 is divided by 3. I went to a Node.js console(version 11.1.0) and a Python console(Python 3.7) and typed in -7 % 3. In the Node.js console, it printed -1, but in the Python console, it printed 2. My question is partially mathematical: Which answer is correct, -1 or 2?

Vappor Washmade
  • 423
  • 4
  • 14

1 Answers1

1

Both are correct, but they are different things. Python uses actual modulus, which is positive. Javascript does a remainder, which can be negative.

If you always need a positive value you can add (a multiple of) the divisor into the value and make sure it’s always larger than zero and will always get the same answer. Or check afterwards for a negative value and add the divisor to get the modulus.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74