(num: number)
| 9 | * @example findFactors(16) = [1,3,5,15] |
| 10 | */ |
| 11 | export const findFactors = (num: number): Set<number> => { |
| 12 | if (num <= 0 || !Number.isInteger(num)) { |
| 13 | throw new Error('Only natural numbers are supported.') |
| 14 | } |
| 15 | |
| 16 | const res: Set<number> = new Set() |
| 17 | // Iterates from 1 to square root of num & pushes factors into the res set. |
| 18 | for (let i = 1; i * i <= num; i++) { |
| 19 | if (num % i === 0) { |
| 20 | res.add(i) |
| 21 | |
| 22 | const sqrtFactor = Math.floor(num / i) |
| 23 | res.add(sqrtFactor) |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | return res |
| 28 | } |