Created
May 6, 2009 11:53
-
-
Save itsthomson/107498 to your computer and use it in GitHub Desktop.
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
#---------------- | |
# euler1.rb | |
# Thomson Nguyen | |
#---------------- | |
# I try to learn ruby by solving Project Euler | |
# puzzles. (http://projecteuler.net) | |
# | |
# Feel free to take a look at my progress and | |
# comment, but don't laugh! | |
# | |
# All code subject to MIT License, blah blah | |
# | |
# | |
# Add all the natural numbers below one thousand that | |
# are multiples of 3 or 5. | |
# | |
# | |
# Brute Force | |
i=0 | |
running=0 | |
while i < 1000 | |
if i.modulo(3)==0 or i.modulo(5)==0 | |
running = running + i | |
end | |
i +=1 | |
end | |
puts running | |
# Using the inclusion-exclusion principle | |
def sumform(n) | |
return n*(n+1)/2 | |
end | |
def sumMultiples(limit,a) | |
return sumform((limit-1)/a) * a | |
end | |
puts sumMultiples(1000, 3) + sumMultiples(1000, 5) - sumMultiples(1000, 15) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment