Last active
July 4, 2016 22:28
-
-
Save durrellchamorro/bc52653717481bb8cbe42281489bdf02 to your computer and use it in GitHub Desktop.
This module can tell if a number is perfect, abundant or deficient according to the Greek mathematician Nicomachus's classification scheme. The algorithm is fast.
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
require 'prime' | |
module PerfectNumber | |
def self.classify(number) | |
raise "Number must be greater than or equal to two" if number < 2 | |
aliquot_sum = generate_aliquot_sum(number) | |
return 'deficient' if aliquot_sum < number | |
return 'abundant' if aliquot_sum > number | |
'perfect' | |
end | |
def self.generate_aliquot_sum(number) | |
primes, exponent_list = number.prime_division.transpose | |
all_exponents = exponent_list.map { |exponent| (0..exponent).to_a } | |
all_exponent_combinations = all_exponents.shift.product(*all_exponents) | |
sum = 0 | |
all_exponent_combinations.each do |exponents| | |
sum += divisor(primes, exponents) | |
end | |
sum -= number | |
end | |
def self.divisor(primes, exponents) | |
primes.zip(exponents) | |
.map { |prime, exponent| prime ** exponent } | |
.reduce(:*) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment