Skip to content

Instantly share code, notes, and snippets.

@bryanwoods
Created September 22, 2008 15:07
Show Gist options
  • Save bryanwoods/12008 to your computer and use it in GitHub Desktop.
Save bryanwoods/12008 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.
def list_of_mults(from, multiple)
from.select {|i| i % multiple == 0 }
end
def check_result(res, multiple)
zeroes = res.collect {|i| i % multiple}
bad_ones = zeroes.select {|i| i != 0}
if bad_ones.length > 0
raise "Wrong multiples in #{res.inspect}"
end
end
def sum_list(initial, list)
list.inject(initial) {|h,g| h+g }
end
start = (1..999).to_a
# All multiples of 3 and then all multiples of 5 in seperate lists ,add sum
x = list_of_mults(start, 3)
y = list_of_mults(start, 5)
check_result(x, 3)
check_result(y, 5)
y_sum = sum_list(0, y)
x_sum = sum_list(0, x)
total = sum_list(x_sum, y)
puts "x should be 63, y should be 50 sum should be 113"
puts "x == #{x_sum}, y=#{y_sum}, total=#{total}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment