Skip to content

Instantly share code, notes, and snippets.

@grumpit
Last active December 20, 2015 20:19
Show Gist options
  • Save grumpit/6189510 to your computer and use it in GitHub Desktop.
Save grumpit/6189510 to your computer and use it in GitHub Desktop.
project euler 28
require 'benchmark'
def build_spiral(spiral_size)
total = 0
spiral_size.step(1, -2) do |i|
v1= i**2
i -= 1
total += i == 0 ? 1 : [v1, v1-i, v1-2*i, v1-3*i].inject{ |sum,x| sum + x }
end
total
end
p build_spiral(1001)
puts Benchmark.measure {build_spiral(1001)}
=> 0.010000 0.000000 0.010000 ( 0.002089)
require 'benchmark'
def build_spiral(spiral_size)
return 1 if spiral_size == 1
total = 1
(3..spiral_size).step(2).to_a.each do |i|
value = i**2
i -= 1
total += (value + (value-i) + (value-2*i) + (value-3*i))
end
total
end
p build_spiral(1001)
puts Benchmark.measure {build_spiral(1001)}
=> 0.000000 0.000000 0.000000 ( 0.000923)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment