Skip to content

Instantly share code, notes, and snippets.

@paulgroves
Last active October 28, 2015 18:35
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 paulgroves/406bdfc8843ab1c38f0a to your computer and use it in GitHub Desktop.
Save paulgroves/406bdfc8843ab1c38f0a 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.
class MulitpleSum
attr_reader :target, :dividers
def initialize(target:, dividers:[])
@target = target
@dividers = dividers
end
def sum
(0...target).map { |x| x if modulus?(x) }.compact.inject(&:+)
end
def modulus?(x)
dividers.map{ |y| x % y == 0 }.any?{ |x| x == true }
end
end
p MulitpleSum.new(target: 1000, dividers: [3,5]).sum # 233168
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment