Check if One Number is Multiple of Another in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20211 min read

Check if One Number is Multiple of Another #

To check if one number is a multiple of another number, use the modulo operator %. The operator returns the remainder when one number is divided by another number. The remainder will only be zero if the first number is a multiple of the second.

index.js
const num1 = 15; const num2 = 5; const remainder = num1 % num2; console.log(remainder); // ๐Ÿ‘‰๏ธ 0 if (remainder === 0) { console.log('๐Ÿ‘‰๏ธ num1 multiple of num2'); } else { console.log('โ›”๏ธ num1 NOT multiple of num2'); }

In the example we use the modulo operator to get the remainder of the division of 2 numbers.

If the remainder after dividing the first by the second number is `0`, we know that the first number is a multiple of the second.

Here are some more examples of using the modulo operator.

index.js
console.log(13 % 5); // ๐Ÿ‘‰๏ธ 3 console.log(12 % 5); // ๐Ÿ‘‰๏ธ 2 console.log(11 % 5); // ๐Ÿ‘‰๏ธ 1 console.log(10 % 5); // ๐Ÿ‘‰๏ธ 0

In the example 10 is a multiple of 5, therefore the division has a remainder of 0.

The modulo operator always takes the sign of the first number (the dividend).

index.js
console.log(-13 % 5); // ๐Ÿ‘‰๏ธ -3 console.log(12 % -5); // ๐Ÿ‘‰๏ธ 2

You might be wondering what happens if we get a remainder of -0. Would our if condition fail, because we only check for 0.

index.js
console.log(-15 % 3); // ๐Ÿ‘‰๏ธ -0

However, 0 is equal to -0 in JavaScript, which means our condition would still work.

index.js
console.log(0 === -0); // ๐Ÿ‘‰๏ธ true

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee