Created
October 26, 2012 20:52
-
-
Save randito/3961422 to your computer and use it in GitHub Desktop.
Ruby perfect_number generator (See http://www.dotkam.com/2012/01/24/clojure-perfect-language-for-perfect-numbers/)
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
#!/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) | |
(1...number).select { |value| number % value == 0 } | |
end | |
range.times do |value| | |
sum_of_divisors = divisors(value).inject { |sum,n| sum + n } | |
puts value if sum_of_divisors == value | |
end | |
end |
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
$ time ./perfect_number.rb 10000 | |
6 | |
28 | |
496 | |
8128 | |
./perfect_number.rb 10000 17.81s user 0.01s system 99% cpu 17.833 total |
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
$ time ./perfect_number.rb 8128 | |
6 | |
28 | |
496 | |
./perfect_number.rb 8128 11.77s user 0.01s system 99% cpu 11.784 total |
Opps. Let's try to 8128.
rpond@Cooper ~/code $ time ./perfect_number.rb 8128
6
28
496
./perfect_number.rb 8128 11.77s user 0.01s system 99% cpu 11.784 total
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See http://www.dotkam.com/2012/01/24/clojure-perfect-language-for-perfect-numbers/
18 seconds for Ruby vs sub-second for Clojure.
I'm sure it could be optimized a bit. lol.