JavaScript Code

How to check if a number if a factor of another?


Problem Statement

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

given two numbers are 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}`);
}