Skip to content

Instantly share code, notes, and snippets.

@dkarpenko
Created June 15, 2013 18:05
Show Gist options
  • Save dkarpenko/5789001 to your computer and use it in GitHub Desktop.
Save dkarpenko/5789001 to your computer and use it in GitHub Desktop.
require 'benchmark'
require "memoize"
include Memoize
UPPER_LIMIT = 1000000
MULTIPLIERS_COUNT = 6
def combinations_count(multipliers_count, upper_limit)
return 1 if multipliers_count == 1
combinations = [0]
(-upper_limit.abs..upper_limit.abs).each do |first_multiplier|
if (first_multiplier != 0 && upper_limit % first_multiplier == 0)
combinations << combinations_count(multipliers_count-1, upper_limit / first_multiplier)
end
end
combinations.inject(:+)
end
puts "Without memoization"
puts Benchmark.measure { puts combinations_count(MULTIPLIERS_COUNT, UPPER_LIMIT) }
memoize(:combinations_count)
puts "With memoization"
puts Benchmark.measure { puts combinations_count(MULTIPLIERS_COUNT, UPPER_LIMIT) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment