Skip to content

Instantly share code, notes, and snippets.

@abdollar
Created December 13, 2011 02:47
Show Gist options
  • Save abdollar/1470247 to your computer and use it in GitHub Desktop.
Save abdollar/1470247 to your computer and use it in GitHub Desktop.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
(400..2432902008176640000).step(20).each do |i|
val = (1..20).to_a.select{|x| i%x==0}&(1..20).to_a
if val.count == 20
puts i
exit
end
end
Use the product of the LCM's
require 'rational'
(1..20).inject(1) { |result, n| result.lcm n }
ruby-1.9.2-p180 :004 > (1..3).inject(1) { |result, n| result.lcm n }
=> 6
ruby-1.9.2-p180 :005 > (1..4).inject(1) { |result, n| result.lcm n }
=> 12
ruby-1.9.2-p180 :006 > (1..5).inject(1) { |result, n| result.lcm n }
=> 60
ruby-1.9.2-p180 :007 > (1..6).inject(1) { |result, n| result.lcm n }
=> 60
ruby-1.9.2-p180 :008 > (1..7).inject(1) { |result, n| result.lcm n }
=> 420
ruby-1.9.2-p180 :009 > (1..8).inject(1) { |result, n| result.lcm n }
=> 840
ruby-1.9.2-p180 :010 > (1..9).inject(1) { |result, n| result.lcm n }
=> 2520
ruby-1.9.2-p180 :011 > (1..10).inject(1) { |result, n| result.lcm n }
=> 2520
ruby-1.9.2-p180 :012 > (1..11).inject(1) { |result, n| result.lcm n }
=> 27720
ruby-1.9.2-p180 :013 > (1..12).inject(1) { |result, n| result.lcm n }
=> 27720
ruby-1.9.2-p180 :014 > (1..13).inject(1) { |result, n| result.lcm n }
=> 360360
ruby-1.9.2-p180 :015 > (1..14).inject(1) { |result, n| result.lcm n }
=> 360360
ruby-1.9.2-p180 :016 > (1..15).inject(1) { |result, n| result.lcm n }
=> 360360
ruby-1.9.2-p180 :017 > (1..16).inject(1) { |result, n| result.lcm n }
=> 720720
ruby-1.9.2-p180 :018 > (1..17).inject(1) { |result, n| result.lcm n }
=> 12252240
ruby-1.9.2-p180 :019 > (1..18).inject(1) { |result, n| result.lcm n }
=> 12252240
ruby-1.9.2-p180 :020 > (1..19).inject(1) { |result, n| result.lcm n }
=> 232792560
ruby-1.9.2-p180 :021 > (1..20).inject(1) { |result, n| result.lcm n }
=> 232792560
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment