Skip to content

Instantly share code, notes, and snippets.

@randito
Created October 26, 2012 20:52
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 randito/3961422 to your computer and use it in GitHub Desktop.
Save randito/3961422 to your computer and use it in GitHub Desktop.
#!/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
$ time ./perfect_number.rb 10000
6
28
496
8128
./perfect_number.rb 10000 17.81s user 0.01s system 99% cpu 17.833 total
$ time ./perfect_number.rb 8128
6
28
496
./perfect_number.rb 8128 11.77s user 0.01s system 99% cpu 11.784 total
@randito
Copy link
Author

randito commented Oct 26, 2012

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.

@randito
Copy link
Author

randito commented Oct 26, 2012

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