Skip to content

Instantly share code, notes, and snippets.

@randito
Created October 26, 2012 21:42
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/3961738 to your computer and use it in GitHub Desktop.
Save randito/3961738 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)
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
$ 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
@randito
Copy link
Author

randito commented Oct 26, 2012

The original unoptimized version => https://gist.github.com/3961422

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment