Skip to content

Instantly share code, notes, and snippets.

@chrisdothtml
Created June 29, 2018 12:25
Show Gist options
  • Save chrisdothtml/6fe75948d93d0d8f41498d040392be3b to your computer and use it in GitHub Desktop.
Save chrisdothtml/6fe75948d93d0d8f41498d040392be3b to your computer and use it in GitHub Desktop.
Perfect number checker
/**
* 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