Created
May 14, 2021 11:22
-
-
Save nitobuendia/e4fe3ed9c93f6b9e253eb740cd0bb412 to your computer and use it in GitHub Desktop.
Prime Factorization
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
/** | |
* Gets all the prime factors of a given number. | |
* @param {number} number for which to get all prime factors. | |
* @param {!Array<number>=} allDivisors List of all prime factors. | |
* This parameter is not meant to be sent when called by a user, but | |
* it is used for the recursive nature of the implementation. | |
*/ | |
const getPrimeFactors = (number, allDivisors = []) => { | |
if (number < 2) throw new Error('getPrimeFactors only accepts numbers greater than 1.'); | |
const maxDivisor = Math.ceil(Math.sqrt(number)); | |
for (let divisor = 2; divisor <= maxDivisor; divisor++) { | |
if (number % divisor === 0 || number % divisor === -0) { | |
allDivisors.push(divisor); | |
const newNumber = number / divisor; | |
return findDivisor(newNumber, allDivisors); | |
} | |
} | |
if (number != 1) allDivisors.push(number); | |
return allDivisors; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment