Skip to content

Instantly share code, notes, and snippets.

@itsthomson
Created May 6, 2009 11:53
Show Gist options
  • Save itsthomson/107498 to your computer and use it in GitHub Desktop.
Save itsthomson/107498 to your computer and use it in GitHub Desktop.
#----------------
# 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