JavaScript Program to Find Factors of a Number
if (number % i === 0) to find factors; for example, for(let i=1; i<=num; i++){ if(num % i === 0) console.log(i); } prints all factors.Examples
How to Think About It
%. If the remainder is zero, that candidate is a factor.Algorithm
Code
function findFactors(num) { const factors = []; for (let i = 1; i <= num; i++) { if (num % i === 0) { factors.push(i); } } return factors; } const number = 12; const result = findFactors(number); console.log(result.join(' '));
Dry Run
Let's trace the number 6 through the code to find its factors.
Initialize factors list
factors = []
Start loop from i=1 to 6
i = 1
Check if 6 % 1 === 0
True, add 1 to factors: factors = [1]
Increment i to 2 and check 6 % 2 === 0
True, add 2: factors = [1, 2]
Increment i to 3 and check 6 % 3 === 0
True, add 3: factors = [1, 2, 3]
Increment i to 4 and check 6 % 4 === 0
False, do not add
Increment i to 5 and check 6 % 5 === 0
False, do not add
Increment i to 6 and check 6 % 6 === 0
True, add 6: factors = [1, 2, 3, 6]
Loop ends, return factors
Return [1, 2, 3, 6]
| i | num % i === 0? | factors |
|---|---|---|
| 1 | true | [1] |
| 2 | true | [1, 2] |
| 3 | true | [1, 2, 3] |
| 4 | false | [1, 2, 3] |
| 5 | false | [1, 2, 3] |
| 6 | true | [1, 2, 3, 6] |
Why This Works
Step 1: Loop through numbers
We use a loop from 1 to the number because factors cannot be larger than the number itself.
Step 2: Check divisibility
Using num % i === 0 checks if the number divides evenly without remainder, which means i is a factor.
Step 3: Collect factors
When a factor is found, we add it to a list to keep track of all factors.
Alternative Approaches
function findFactorsSqrt(num) { const factors = []; for (let i = 1; i <= Math.sqrt(num); i++) { if (num % i === 0) { factors.push(i); if (i !== num / i) { factors.push(num / i); } } } return factors.sort((a,b) => a - b); } console.log(findFactorsSqrt(12).join(' '));
function findFactorsRec(num, i = 1, factors = []) { if (i > num) return factors; if (num % i === 0) factors.push(i); return findFactorsRec(num, i + 1, factors); } console.log(findFactorsRec(12).join(' '));
Complexity: O(n) time, O(n) space
Time Complexity
The loop runs from 1 to n, so it takes O(n) time. Each iteration does a simple modulo check.
Space Complexity
We store factors in a list which can hold up to n elements in the worst case (e.g., number 1).
Which Approach is Fastest?
Checking up to the square root reduces time to O(√n), making it faster for large numbers compared to the simple O(n) loop.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop 1 to n | O(n) | O(n) | Small to medium numbers, easy to understand |
| Loop up to sqrt(n) | O(√n) | O(n) | Large numbers, better performance |
| Recursion | O(n) | O(n) | Learning recursion, not for large inputs |