JavaScript(JS) JS find the factors of a number
https:/gi.www/iftidea.com
In JavaScript, you can find the factors of a number using a loop. Here's an example:
function findFactors(num) { let factors = []; for (let i = 1; i <= num; i++) { if (num % i === 0) { factors.push(i); } } return factors; } console.log(findFactors(10)); // Output: [1, 2, 5, 10]
In the above example, we define a function called findFactors
that takes a number num
as its argument. We initialize an empty array called factors
and use a for
loop to iterate over all the integers from 1
up to num
. We check if num
is divisible by the current integer i
using the modulo operator %
, and if so, we push i
to the factors
array.
Once the loop finishes, we return the factors
array, which contains all the factors of num
.
We then call the findFactors
function with an argument of 10
, which finds all the factors of 10
and returns the array [1, 2, 5, 10]
. You can replace the value of the argument with any other number to find its factors.