Created
June 29, 2018 12:25
-
-
Save chrisdothtml/6fe75948d93d0d8f41498d040392be3b to your computer and use it in GitHub Desktop.
Perfect number checker
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
/** | |
* Indicates whether the sum of the factors of a number | |
* are equal to the number | |
* https://en.wikipedia.org/wiki/Perfect_number | |
* | |
* @param {Number} num | |
* @returns {Boolean} | |
*/ | |
function isPerfectNumber (num) { | |
const numRoot = Math.sqrt(num) | |
const isEven = num % 2 === 0 | |
const incr = isEven ? 1 : 2 | |
let factorsSum = 1 | |
for (let factor = isEven ? 2 : 3; factor <= numRoot; factor += incr) { | |
if (num % factor === 0) { | |
const compliment = num / factor | |
factorsSum += factor | |
if (compliment !== factor) { | |
factorsSum += compliment | |
} | |
} | |
} | |
return factorsSum === num | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment