Get factors of number
11 March 2022 (Updated 20 November 2022)
You want a function that takes an integer and returns all its factors from one up to the number itself. Something like this:
getFactors(20) // [1, 2, 4, 5, 10, 20]
getFactors(121) // [1, 11, 121]
Here’s how:
function getFactors(num) {
const factors = []
for (let n = 1; n <= num; n++) {
if (num % n === 0) {
factors.push(n)
}
}
return factors
}
Tagged:
Snippets
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment