Skip to content

Instantly share code, notes, and snippets.

@chrisdothtml
Last active June 29, 2018 12:22
Show Gist options
  • Save chrisdothtml/96635f8f83e3e7eb10a574d339b79a3a to your computer and use it in GitHub Desktop.
Save chrisdothtml/96635f8f83e3e7eb10a574d339b79a3a to your computer and use it in GitHub Desktop.
Get all factors of a number
/**
* Get all factors of a number
*
* @param {Number} num
* @returns {Set}
*/
function getFactors (num) {
const numRoot = Math.sqrt(num)
const isEven = num % 2 === 0
const incr = isEven ? 1 : 2
const result = new Set([1, num])
for (let factor = isEven ? 2 : 3; factor <= numRoot; factor += incr) {
if (num % factor === 0) {
const compliment = num / factor
result.add(factor)
if (compliment !== factor) {
result.add(compliment)
}
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment