Check if a number is a factor of another in JavaScript
In this tutorial, you are given two numbers. Write a JavaScript program to check if the first number is a factor of the second number.
Solution
To check if the first number is a factor of second number, the first number must leave a remainder of 0 when it divides the second number.
We will use arithmetic modulus operator to find the remainder of the division (second number / first number), and use equal-to comparison operator to check if the remainder is equal to zero.
Program
In the following program, we are given two numbers in num1
and num2
. Check if num1
is a factor of num2
.
let num1 = 7;
let num2 = 84;
if ( num2 % num1 == 0 ) {
console.log(`${num1} is a factor of ${num2}`);
} else {
console.log(`${num1} is not a factor of ${num2}`);
}