Forked from anonymous/Find Perfection (1.6 Extra Problems).js
Created
July 31, 2016 18:46
-
-
Save sethschori/30cb25ff4f5b2bd1fb6090c95407b477 to your computer and use it in GitHub Desktop.
https://repl.it/CZ1s/52 created by sethopia
This file contains hidden or 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
/* | |
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)); |
This file contains hidden or 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
Native Browser JavaScript |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment