Skip to content

Instantly share code, notes, and snippets.

@ingo-eichhorst
Last active March 26, 2019 09:59
Show Gist options
  • Save ingo-eichhorst/4f68582566687bd654844a862be26a5d to your computer and use it in GitHub Desktop.
Save ingo-eichhorst/4f68582566687bd654844a862be26a5d to your computer and use it in GitHub Desktop.
Calculating prime factors of a given number recursively @ Software Craftsmanship Berlin Meetup (2019-03-25)
/**
* Calculates the prime factors for a given number.
* - Note: Currently the function will chrash with numbers greater than ~2000 because of the recursive nature.
* - This could potentially be optimized with e.g. proper tail calls
*
* @param {number} number - number used to calculate the prime factors
* @returns {array} primeFactors
*/
function calculatePrimeFactor (number, prime = 2, results = []) {
if (number >= prime && number % prime === 0) {
results.push(prime)
if (prime !== number) {
return calculatePrimeFactor(number/prime, prime, results)
} else return results
} else if (number > prime) {
return calculatePrimeFactor(number, prime+1, results)
} else return results
}
/**
* Test the primeFactor function
*
* @param {object} tests - the property is the number to test and the value is the expected result
*/
function runTests (tests) {
let errors = 0
Object.keys(tests).forEach(test => {
const aim = tests[test].toString()
const testResult = calculatePrimeFactor(Number(test)).toString()
if (testResult !== aim) {
errors++
console.log(`FAIL: Expected ${aim} - got ${testResult}`)
}
else console.log(`OK: Expected ${aim} - got ${testResult}`)
})
if(errors > 0) throw 'test failed'
console.log('test succeed')
}
runTests({
0: [],
1: [],
2: [2],
4: [2,2],
6: [2,3],
8: [2,2,2],
11: [11],
12: [2,2,3],
16: [2,2,2,2],
250: [2,5,5,5],
275: [5,5,11],
1111: [11,101],
1122: [2,3,11,17],
1987: [1987],
// 105733: [105733] // this will chrash with RangeError: Maximum call stack size exceeded
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment