Home > OS >  Negative number modulo 2
Negative number modulo 2

Time:09-04

Admittedly my maths is not that strong. Why do these two examples give differing results?

Example One

function isOdd(num) {
  return (num % 2) == 1 ? true : false;
}
console.log(isOdd(-17));

Output: false (incorrect)

Example Two

function isOdd(num) {
  return (num % 2) != 0 ? true : false;
}
console.log(isOdd(-17));

Output: true (correct)

Console Test

console.log(-17 % 2);

The output was -1, rather than 1.

Any odd number mod 2 always equals 1, does it not? So why is this happening? Why do I need to test for != 0 in order to get the right answer? Why does == 1 yield a wrong answer?

CodePudding user response:

The explanation I found on MDN Documentation concerning the mod operator in javascript is that the returned value takes the sign of the dividend (the number being divided: -17 in your case).

This is the same in mathematics when you are dividing -17/2. The answer is -8.5, and if you only want the whole number, then you will get -8 - 1/2. Meaning that -1 is the remaining of your division.

You will find the same answer in C and Go Programming languages.

I do not know why Python does return 1 in such a case. My opinion is python only returns the integer value and ignores the sign.

It is safe to say a number is odd when the remainder is different from 0.

  • Related