Skip to content

Instantly share code, notes, and snippets.

@durrellchamorro
Last active July 4, 2016 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durrellchamorro/bc52653717481bb8cbe42281489bdf02 to your computer and use it in GitHub Desktop.
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.
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