Checking the division remainder in JavaScript
Suppose we have two variables with numbers:
let a = 10;
let b = 3;
Let's find the remainder after dividing one variable by another:
let a = 10;
let b = 3;
console.log(a % b); // shows 1
Let now the variables store such values that one variable is divided by the second completely:
let a = 10;
let b = 5;
console.log(a % b); // shows 0
Let's write a script that will check if one number is divisible by the second:
let a = 10;
let b = 3;
if (a % b === 0) {
console.log('is divisible');
} else {
console.log('is divided with a remainder');
}
Let now it is required, if the number is divided with the remainder, output this remainder to the console:
let a = 10;
let b = 3;
if (a % b === 0) {
console.log('is divisible');
} else {
console.log('is divided with a remainder ' + a % b);
}
In the code above, it turns out that the remainder is calculated in two places, and this is not optimal. Let's fix the problem:
let a = 10;
let b = 3;
let rest = a % b;
if (rest === 0) {
console.log('is divisible');
} else {
console.log('is divided with a remainder ' + rest);
}
As you know, even numbers are divided
by 2
without a remainder, and
odd numbers with a remainder. Let's say
you have a number. Use the operator
%
and the construct if
to check if this number is even or not.
Given a number. Check that it is
divisible by 3
.