We are required to write a JavaScript function that takes in a positive integer as the only argument. The function should construct and return an array of all the numbers that exactly divide the input number.
For example −
If the input number is −
const num = 12;
Then the output should be −
const output = [1, 2, 3, 4, 6, 12];
Example
Following is the code −
const findFactors = (num = 1) => { let half = Math.floor(num / 2); const res = [1]; // 1 will be a part of every solution. let i, j; num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2); for (i; i <= half; i += j) { if(num % i === 0){ res.push(i); }; }; res.push(num); return res; }; console.log(findFactors(12));
Output
Following is the output on console −
[ 1, 2, 3, 4, 6, 12 ]