Created
February 14, 2011 03:15
-
-
Save michaeltwofish/825434 to your computer and use it in GitHub Desktop.
Euler problem 1
This file contains hidden or 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
# Brute force | |
sum = 0 | |
(1..999).each do |num| | |
sum = sum + num if (num % 3 == 0 || num % 5 == 0) | |
end | |
puts "Brute force: #{sum}" | |
# More rubyish, but still brute force | |
sum = (1..999).inject(0) {|sum,num| (num % 3 == 0 || num % 5 == 0) ? sum + num : sum} | |
puts "More rubyish but still brute force: #{sum}" | |
# Smart way | |
def divisible_sum(num, max) | |
occ = max/num | |
occ.to_f/2 * (num + (num * occ)) | |
end | |
sum = divisible_sum(3, 1000) + divisible_sum(5, 1000) - divisible_sum(15, 1000) | |
puts "Smarter: #{sum}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment