Last active
July 4, 2016 22:57
-
-
Save durrellchamorro/7bd17db16663e33346cf1efd3a7dc69e to your computer and use it in GitHub Desktop.
This program can tell if a number is perfect, abundant or deficient according to the Greek mathematician Nicomachus's classification scheme. This algorithm is fast, but its speed pales in comparison to the algorithm I wrote that uses ruby's Prime class.
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 'benchmark' | |
class PerfectNumber | |
def self.classify(number) | |
raise RuntimeError if number <= 1 | |
sum_of_divisors = add_divisors(number) | |
return 'deficient' if sum_of_divisors < number | |
return 'abundant' if sum_of_divisors > number | |
'perfect' | |
end | |
def self.add_divisors(number) | |
sqrt_of_number = Math.sqrt(number) | |
range = 2..sqrt_of_number.floor | |
sum_of_divisors = 1 | |
range.each do |divisor_candidate| | |
next unless number % divisor_candidate == 0 | |
sum_of_divisors += divisor_candidate | |
sum_of_divisors += | |
number / divisor_candidate unless divisor_candidate == sqrt_of_number | |
end | |
sum_of_divisors | |
end | |
private_class_method :add_divisors | |
end | |
time = Benchmark.measure do | |
PerfectNumber.classify(999_999_999_999_999_999) | |
end | |
p time # => #<Benchmark::Tms:0x007fab228bfb58 @label="", @real=64.7947408069158, @cstime=0.0, @cutime=0.0, @stime=0.05, @utime=64.69999999999999, @total=64.74999999999999> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment