Reputation: 15118
Im currently in process of learning Javascript. And I have seen the following code, which confuses me.
Description of code:
Starting on line 1, the function isOdd takes a number n and returns a boolean (true or false) stating whether the number is odd or not.
Code
var isOdd = function (n) {
if (n % 2 === 0) {
return false;
} else {
return true;
}
};
var isEven = function(n) {
if(n % 2 === 0) {
return true;
} else {
return false;
}
};
Where I am confused.
The code:
n % 2 === 0
I have always taken the following to be the description for %:
% Is the modulus operator. It returns the remainder of dividing number1 by number2.
Which would mean that the if statement in the function isOdd returns false is the difference between n and 2 is 0. But its meant to mean if n is divisible by 2 (even) return false.
I just dont see how its doing that.
In my mind, if we take the even number 30. Apply it to n % 2. We get 15, which is remainder of dividing 30 by 2. 15 does not equal 0, but 30 is an even number, and with this code it would be seen as odd.
Can someone explain this?
Upvotes: -1
Views: 6734
Reputation: 22461
You're confusing Quotient and Remainder. When you divide 30 by 2, integer quotient is 15, and remainder is 0. You can also calculate remainder by multiplying integer quotient by divisor and subtracting it from dividend. So for this division remainder is 30 (dividend) - 15 (quotient) * 2 (divisor) = 0.
Upvotes: 1
Reputation: 21138
The line in question:
if (n % 2 === 0) {
return false;
}
Means "if when you divide n by 2 the remainder is zero, then return false (i.e. n is not odd)".
The "remainder" is whatever is left over when you subtract the nearest multiple, so for example "64 % 10" is 4, since the nearest multiple of 10 is 60, leaving 4.
Taking your example and putting it another way, 30/2 is 15, 30%2 is zero (i.e. whatever is left over after 30/2). Here's more info on the remainder after division.
Upvotes: 3
Reputation: 16915
If n can be divided by 2 it means it's even ->
which means it's not odd ->
isOdd is false
Upvotes: 0