JS Example for Beginners: JavaScript Program to Find the Factors of a Number

(JavaScript programming Example for Beginners)

JavaScript Program to Find the Factors of a Number

In this example, you will learn to write a JavaScript program that finds all the factors of an integer.


To be the factors of a number, the factor number should exactly divide the number (with 0 remainder). For example,

The factor of 12 is 12346, and 12.

Example: Factors of Positive Number

// program to find the factors of an integer

// take input
let num = prompt('Enter a positive number: ');

console.log(`The factors of ${num} is:`);

// looping through 1 to num
for(let i = 1; i <= num; i++) {

    // check if number is a factor
    if(num % i == 0) {
        console.log(i);
    }
}

Output

Enter a positive number: 12
The factors of 12 is:
1
2
3
4
6
12

In the above program, the user is prompted to enter a positive integer.

  • The for loop is used to loop through 1 to the number entered by the user.
  • The modulus operator % is used to check if num is exactly divisible.
  • In each iteration, a condition is checked if num is exactly divisible by i.
  • if(num % i == 0)
  • If the above condition is met, the number is displayed.

 

JS Example for Beginners: JavaScript Program to Find the Factors of a Number

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.