Skip to content

Instantly share code, notes, and snippets.

@jwg2s
Created August 4, 2012 08:19
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 jwg2s/3255854 to your computer and use it in GitHub Desktop.
Save jwg2s/3255854 to your computer and use it in GitHub Desktop.
require 'benchmark'
def count_factors(number)
factors = (1..number).select { |n| (number % n).zero? }
factors.count
end
def print_doors(n)
i = 0
array = (1..n)
array.each do |door|
puts "Door ##{door} is #{count_factors(door).even? ? "closed" : "open" }." #=> This is not.
end
end
n = 8000
Benchmark.bm do |x|
x.report { print_doors(n) }
x.report do
(1..n).each do |i|
puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}" #=> This is optimized.
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment