Created
October 26, 2012 21:42
-
-
Save randito/3961738 to your computer and use it in GitHub Desktop.
Optimized Ruby perfect_number generator (See http://www.dotkam.com/2012/01/24/clojure-perfect-language-for-perfect-numbers/)
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
#!/usr/bin/env ruby -wKU | |
if __FILE__ == $PROGRAM_NAME | |
range = ARGV.first.to_i | |
raise 'Usage: perfect_number.rb [range]' unless range != 0 | |
def divisors(number) | |
sqrt = Math.sqrt(number) + 1 # divsors come in pair.. so we can optimize | |
lower_factors = (1..sqrt).select { |value| number % value == 0 } | |
upper_factors = lower_factors.map { |value| number / value } # i.e. | |
(lower_factors + upper_factors).uniq | |
end | |
range.times do |value| | |
sum_of_divisors = divisors(value).inject { |sum,n| sum + n } | |
puts value if sum_of_divisors == 2 * value | |
end | |
end |
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
$ time ./perfect_number.rb 8028 | |
6 | |
28 | |
496 | |
./perfect_number.rb 8028 0.53s user 0.01s system 99% cpu 0.544 total | |
This optimized version is *much* better than the original at https://gist.github.com/3961422 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The original unoptimized version => https://gist.github.com/3961422