How to usea While Loop in Javascript
In this approach, we utilize a while loop to find the factors of the input number. We start iterating from 1 and continue until reaching the input number. For each iteration, we check if the input number is divisible by the current iteration value with a remainder of 0. If it is, then the current iteration value is a factor of the input number, and we add it to the list of factors.
Example: This example demonstrates the utilization of a while loop to find the factors of a given input number.
let n = 12;
let i = 1;
let factors = [];
while (i <= n) {
if (n % i === 0) {
factors.push(i);
}
i++;
}
console.log(factors);
Output
[ 1, 2, 3, 4, 6, 12 ]
JavaScript Program to Find the Factors of a Number
We have given the input number and we need to find all the factors of that number. Factors of the number are nothing but the numbers that divide the original input number evenly with the remainder of 0. Below we have added the example for better understanding:
Example:
Input: n = 10
Output: 1 2 5 10
Input: n = 12
Output: 1 2 3 4 6 12
Table of Content
- Using For Loop
- Using Spread Operator
- Using the reduce method
- Using the map method
Contact Us