Signup/Sign In
PUBLISHED ON: JANUARY 17, 2023

JavaScript Program to Find the Factors of a Number

We will learn how to write a JavaScript program that can find the factors of a given number in this tutorial. A number's factors are the integers that divide it exactly without leaving any remainder. The program will take a number from the user and use mathematical algorithms to find all the factors of that number.

The steps for writing the program, including the logic and syntax used to find the factors, will be covered in this tutorial. You will be able to write a JavaScript program that can find the factors of any number by the end of this tutorial.

We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.

What is a Factor of a Number?

A factor is a number that divides another number, leaving no remainder. In other words, if multiplying two whole numbers gives us a product, then the numbers we are multiplying are factors of the product because they are divisible by the product.

Note: There is no reminder left after a number is divisible by its factor.

The factor of 15 is 1, 3, 5, and 15.

Approach

The user is asked for the number.

  • A for Loop is run from 1 to the number itself which was entered by the number.
  • The modulus operator % is used to check if the num is exactly divisible or not.
  • In each iteration, a condition is checked if the num is exactly divisible by i.

Program to Find the Factors of a Number

// JavaScript program to find the factors of an integer

const num = prompt('Enter a positive number: ');

console.log("The factors of "+ num + "is ");

for(let i = 1; i <num; i++) {

    // checking if the number is a factor or not. 
    if(num % i == 0) 
        console.log(i);
 }
 console.log(num);


Enter a positive number: 18
The factors of 18 is:
1
2
3
6
9
18

Conclusion

Finally, we learned how to create a JavaScript program that finds the factors of a given number. The program accepts a number from the user and employs mathematical algorithms to determine all of the number's factors. We've talked about the logic and syntax used in the program, which involves using a loop to divide the number by integers beginning with 1 and ending with the number itself, and then checking to see if the division leaves no remainder.

This can be useful in a variety of mathematical and computational applications, as well as in better understanding the concept of factors.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.