Skip to content

Instantly share code, notes, and snippets.

@leandronsp
Created December 4, 2021 15:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leandronsp/4186b00361758a70a0518b0f419de9bd to your computer and use it in GitHub Desktop.
Save leandronsp/4186b00361758a70a0518b0f419de9bd to your computer and use it in GitHub Desktop.
Sum all numbers in a consecutive range
require 'benchmark'
def sum_range_using_for_loop(min, max)
range = (min..max)
sum = 0
for n in range
sum = sum + n
end
sum
end
def sum_range_using_math(min, max)
sum_max = max * (1 + max) / 2
sum_min = min * (1 + min) / 2
sum_max - sum_min + min
end
min = 1
max = 123456789
Benchmark.bm do |x|
x.report('for loop') { sum_range_using_for_loop(min, max) }
x.report('math') { sum_range_using_math(min, max) }
end
#### Results #####
#------> for loop: 6.87s
#------> math: 0.000008s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment