Skip to content

Instantly share code, notes, and snippets.

@bryanwoods
Created September 22, 2008 15:06
Show Gist options
  • Save bryanwoods/12007 to your computer and use it in GitHub Desktop.
Save bryanwoods/12007 to your computer and use it in GitHub Desktop.
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
start = (1..999).to_a
# x = [ 3, 6, 9, 12, 15, 18 ]
# y = [ 5, 10, 15, 20 ]
# All multiples of 3 and then all multiples of 5 in seperate lists ,add sum
# first go through the list and find the 3's putting them in a new list
x = []
for i in start
if i % 3 == 0
x << i
end
end
# second, go through and find the 5's putting them in a new list
y = []
start.each {|i| y << i if i % 5 == 0 }
# THE OTHER WAY: y = start.select {|i| i % 5 == 0 }
# then, print a check that makes sure they are multiples
# finally add them together and print the answer
x_sum = x.inject {|h,g| h+g }
y_sum = y.inject(0) {|h,g| h+g}
as_zeros = y.collect {|i| i % 5} + x.collect{|i| i % 3}
bad_ones = as_zeros.select {|i| i != 0}
if bad_ones.length > 0
puts "ERROR:"
puts bad_ones.inspect
end
puts "x should be 63, y should be 50 sum should be 113"
puts "x == #{x_sum}, y=#{y_sum}, total=#{x_sum + y_sum}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment