I understand the basic concept of modulo: It give you the remainder with division. I don't seem to be able to grasp how to use it correctly in practice. For instance, the following code takes a number and if it divides evenly by 2 it will return true, otherwise it returns false:
if(number % 2){
return false;
}
else{
return true;
}
It seems to me intuitively (and wrongly) that the way you would code it would be to set it so the modulo works out to 0:
if (number/2 %0) {
return true
Can anyone explain how and why the first one is correct? Keep in mind that I am obviously extremely dense ...
To check if a number divides without leaving a remainder you need to check if the result of the modulo devision is equal to zero.
if ((number % 2) == 0){
return true; // number was even
} else {
return false; // number was odd
}
From mdn % remainder documentation:
The remainder operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables. The modulo function is the integer remainder of dividing var1 by var2.
Taking that in mind, here are the results of using % with a few values:
59 % 2
> 1
60 % 2
> 0
0 is a falsey value in javascript, so the the result of 60 %2 is never going to pass your if test. To make a proper comparison you'll need to directly check if you have a value of 0:
if (number % 2 === 0)
return true
When you use the modulo (%) operator, you are basically saying:
number % x:
Divide number by x. Round the result down to nearest integer. Multiply that integer by x. Give me the distance (absolute value) of this number to the original number.
This might not be the exact mathematical definition of modulo, but I would like to believe it is pretty close for our needs.
To give a few examples...
2 % 2 = 0 (2 / 2 = 1, 1 * 2 = 2, abs(2 - 2) = 0)
3 % 2 = 1 (3 / 2 ≐ 1, 1 * 2 = 2, abs(2 - 3) = 1)
4 % 2 = 0 (4 / 2 = 2, 2 * 2 = 4, abs(4 - 4) = 0)
The problem with your notation is that it is one extra operation that needs to be performed by the programmer. Since the current way we express the modulo operation is quite concise and does not require us to do any divisions ourselves, there is potential for performance optimisations to be done under the hood.
To express what I believe is your intent, you basically calculate the modulo with the current syntax and compare it to a particular value:
if (number % 2 === 0)
return true // Yup, its divisible by 2
Building on top of the other answers, I'd like to mention that using an if / else to explicitly return a boolean value, when you've already evaluated a boolean value, is overly verbose.
If all you are doing in the if / else is returning a boolean on either side, then your return expression can be reduced.
Good:
function isEven(num) {
return (num % 2 === 0);
}
function isOdd(num) {
return (num % 2 !== 0);
}
Bad:
function badIsEven(num) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}
Related
could you please help me understand why the following line result is [1,3]?
[1,3,6].filter( item => item % 2)
I was expecting to receive the even number from the array.
Many thanks!
Filter checks for a boolean, 3 % 2 is equal to 1, which evaluates to true.
You want item % 2 == 0
Even numbers are those numbers that are exactly divisible by 2.
The remainder operator % gives the remainder when used with a number. For example,
const number = 6;
const result = number % 4; // 2
Hence, when % is used with 2, the number is even if the remainder is zero. Otherwise, the number is odd.
// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");
//check if the number is **even**
if(number % 2 == 0) {
console.log("The number is even.");
}
// if the number is **odd**
else {
console.log("The number is odd.");
}
ref : https://www.programiz.com/javascript/examples/even-odd
How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.
Use modulus:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0
Seriously, there's no jQuery plugin for odd/even checks?
Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test-suites are available at http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* #args number n
* #return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* #args number n
* #return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();
You don't need jQuery. Just use JavaScript's Modulo operator.
You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
You can do it in a better way (up to 50 % faster than modulo operator):
odd: x & 1
even: !(x & 1)
Reference: High Performance JavaScript, 8. ->Bitwise Operators
You can also:
if (x & 1)
itsOdd();
else
itsEven();
if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
var x = 2;
x % 2 ? oddFunction() : evenFunction();
Please write the following code in your console:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
Please Note: It will return true, if the entered number is even otherwise false.
Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
ruby :D
2
4
6
8
10
Should add all the natural numbers below 1000 that are multiples of 3 or 5.
var sum = _.reduce( _.range(1, 1000), function(x, n) {
if (n % 3 == 0 || n % 5 == 0) { return x+=n; }
}, 0);
I expect the output to be 233168 but I get NaN.
For some reason sum is not accepting the initialized value of 0. However if I preface this with var sum = 0; then it works and returns the proper output of 233168
Why doesn't it accept the initialized value?
The problem is the reducing function returns undefined when the conditional fails .. thus x evaluates to undefined (the last return value) in the subsequent invocation .. and undefined + a number is .. well, NaN.
Also, reduce is being used incorrectly; it should carry its own state. Compare it with:
var sum = _.reduce( _.range(1, 1000), function(x, n) {
// Add n to the tally if it is a valid multiple..
// (the returned value is used as the *next* value of x)
if (n % 3 == 0 || n % 5 == 0) { return x + n; }
// ..or simply return the current tally.
else { return x; }
}, 0);
Note that the sum variable was not assigned from within the reducing function (it would have been overwritten by the outside assignment anyway). This keeps reduce a pure operation, not withstanding the occasional abuse of a mutable memo, truer to its functional roots.
I've been trying to write code that multiplies even indexed elements of an array by 2 and odd indexed elements by 3.
I have the following numbers stored in the variable number, which represents an array of numbers
numbers = [1,7,9,21,32,77];
Even Indexed Numbers - 1,9,32
Odd Indexed Numbers - 7, 21, 77
Please keep in mind that arrays are Zero Indexed, which means the numbering starts at 0. In which case, the 0-Indexed element is actually 1, and the 1-Indexed element is 7.
This is what I expected the output to be
[2,21,18,63,64,231]
Unfortunately, I got this output
[2,14,17,42,64,154]
Here is the code for my method
numbers = numbers.map(function(x) {
n = 0;
while (n < numbers.length) {
if (n % 2 == 0) {
return x * 2;
}
else {
return x * 3;
}
n++;
}});
return numbers;
Here I created a while loop, that executes code for every iteration of the variable n. For every value of the variable n, I'm checking if n is even, which is used by the code n % 2 == 0. While it's true that 0 % 2 == 0 it's not true that 1 % 2 == 0. I'm incrementing n at the end of the while loop, so I don't understand why I received the output I did.
Any help will be appreciated.
You created a global property called n, by doing
n = 0;
and then,
while (n < numbers.length) {
if (n % 2 == 0) {
return x * 2;
} else {
return x * 3;
}
}
n++; // Unreachable
you always return immediately. So the, n++ is never incremented. So, n remains 0 always and so all the elements are multiplied by 2 always.
The Array.prototype.map's callback function's, second parameter is the index itself. So, the correct way to use map is, like this
numbers.map(function(currentNumber, index) {
if (index % 2 === 0) {
return currentNumber * 2;
} else {
return currentNumber * 3;
}
});
The same can be written succinctly, with the ternary operator, like this
numbers.map(function(currentNumber, index) {
return currentNumber * (index % 2 === 0 ? 2 : 3);
});
To complement the other answer, the source of OP's confusion is on how "map" works. The map function is already called for each element - yet, OP attempted to use a while loop inside it, which is another way to iterate through each element. That is a double interaction, so, in essence, if OP's code worked, it would still be modifying each number n times! Usually, you just chose between a loop or map:
Using a loop:
var numbers = [1,7,9,21,32,77];
for (var i=0; i<numbers.length; ++i)
numbers[i] = i % 2 === 0 ? numbers[i] * 2 : numbers[i] * 3;
Using map:
var numbers = [1,7,9,21,32,77];
numbers.map(function(number, index){
return number * (index % 2 === 0 ? 2 : 3);
});
Or, very briefly:
[1,7,9,21,32,77].map(function(n,i){ return n * [2,3][i%2]; });
Basically you want to return a modified array that if the elements of the initial one is:
in even position, then multiply the element by 2.
in odd position, then multiply the element by 3.
You can use map with arrow functions and the conditional (ternary) operator to get this one-liner
console.log([1,7,9,21,32,77].map((num,ind) => num * (ind % 2 === 0 ? 2 : 3)));
This will output the desired
[2, 21, 18, 63, 64, 231]
How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.
Use modulus:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0
Seriously, there's no jQuery plugin for odd/even checks?
Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test-suites are available at http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* #args number n
* #return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* #args number n
* #return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();
You don't need jQuery. Just use JavaScript's Modulo operator.
You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
You can do it in a better way (up to 50 % faster than modulo operator):
odd: x & 1
even: !(x & 1)
Reference: High Performance JavaScript, 8. ->Bitwise Operators
You can also:
if (x & 1)
itsOdd();
else
itsEven();
if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
var x = 2;
x % 2 ? oddFunction() : evenFunction();
Please write the following code in your console:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
Please Note: It will return true, if the entered number is even otherwise false.
Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
ruby :D
2
4
6
8
10