Last active
June 29, 2018 12:22
-
-
Save chrisdothtml/96635f8f83e3e7eb10a574d339b79a3a to your computer and use it in GitHub Desktop.
Get all factors of a number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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