Created
June 12, 2015 14:41
-
-
Save tncbbthositg/3d8daeaae7149b6fcc09 to your computer and use it in GitHub Desktop.
Solutions to 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
require 'benchmark' | |
def plain_map n | |
# Enter your code here. Read input from STDIN. Print output to STDOUT | |
three_or_five = -> i {i % 3 == 0 || i % 5 == 0} | |
total = (0...n.to_i).inject(0) do |sum, i| | |
next sum unless three_or_five.call(i) | |
sum + i | |
end | |
end | |
def threes_and_non_three_fives n | |
threes = (3...n).step(3).inject(&:+) | |
fives = (5...n).step(5).select{|i| i % 3 != 0}.inject(&:+) | |
threes + fives | |
end | |
def threes_fives_no_fifteens n | |
threes = (3...n).step(3).inject(0, &:+) | |
fives = (5...n).step(5).inject(0, &:+) | |
fifteens = (15...n).step(15).inject(0, &:+) | |
threes + fives - fifteens | |
end | |
def partial_sum(base, max) | |
top = max / base | |
sum = Rational(top, 2) * (top + 1) | |
sum.floor * base | |
end | |
def computed n | |
threes = partial_sum 3, n | |
fives = partial_sum 5, n | |
fifteens = partial_sum 15, n | |
threes + fives - fifteens | |
end | |
n = 10_000_000 | |
Benchmark.bm(30) do |bm| | |
bm.report('plain_map') { plain_map n } | |
bm.report('threes_and_non_three_fives') { threes_and_non_three_fives n } | |
bm.report('threes_fives_no_fifteens') { threes_fives_no_fifteens n } | |
bm.report('computed') { computed n } | |
end | |
# user system total real | |
#plain_map 2.750000 0.020000 2.770000 ( 2.833699) | |
#threes_and_non_three_fives 0.720000 0.010000 0.730000 ( 0.738672) | |
#threes_fives_no_fifteens 0.540000 0.000000 0.540000 ( 0.555927) | |
#computed 0.000000 0.000000 0.000000 ( 0.000019) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment