Skip to content

Instantly share code, notes, and snippets.

Created July 31, 2016 18:46
Show Gist options
  • Save anonymous/d61eb237f6210dbf4f3dc20e420c8725 to your computer and use it in GitHub Desktop.
Save anonymous/d61eb237f6210dbf4f3dc20e420c8725 to your computer and use it in GitHub Desktop.
https://repl.it/CZ1s/52 created by sethopia
/*
PERFECT NUMBERS
A 'Perfect' number is a number whose sum of their divisors equals exactly that number. The divisors do not include the number itself
ex)
6 is perfect because 1 + 2 + 3 === 6
16 is not perfect because 1 + 2 + 4 + 8 === 15
An "Abundant" number is a number whose sum of their divisors (exluding itself) is greater than that number
ex)
20 is abundance because 1 + 2 + 4 + 5 + 10 === 22 and 22 > 20
A "Deficient" number is a number whose sum of their divisors (excluding itself) is less than that number
ex)
16 is deficiant because 1 + 2 + 4 + 8 === 15 and 15 < 16
Create a function findPerfect() that takes a number as input and returns "Perfect" if the number is perfect, "Abundance" if it is abundant and "Deficient" if it is deficient
ex)
findPerfect(6) --> "Perfect"
findPerfect(20) --> "Abundant"
findPerfect(16) --> "Deficient"
*/
function findPerfect(n) {
var divisors = []; // a better solution shown in this Problem's solution is just to += to a sum, not bother with an array
for (var i = 1; i < n; i++) {
if (n % i === 0) {
divisors.push(i);
}
}
var sum = divisors.reduce(function(a,b){return a + b});
if (sum > n) return "Abundant";
if (sum < n) return "Deficient";
return "Perfect";
}
console.log("Perfect",findPerfect(6));
console.log("Abundant",findPerfect(20));
console.log("Deficient",findPerfect(16));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment