Created
November 24, 2012 06:16
-
-
Save edalorzo/4138638 to your computer and use it in GitHub Desktop.
Project Euler-Problem 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Given a maximum integer m and a factor n, calculates the sum | |
# of all divisors of n up to m. | |
def sumDivisible(m,n) | |
p = m / n | |
n * (p * (p + 1)) / 2 | |
end | |
def solve | |
result = sumDivisible(999,3) + sumDivisible(999,5) - sumDivisible(999, 15) | |
"The sum of multiples of 3 and 5 up to 1000 is: #{result}" | |
end | |
# Naive alternative solution based on filtering a range. | |
def alternative(j,k,m) | |
sum = 0 | |
1.upto(m-1) do |n| | |
if n % j == 0 || n % k == 0 then | |
sum += n | |
end | |
end | |
sum | |
end | |
puts solve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment