Ruby sum is a sober and amazing story

Introduction

The story that sum, which has a reputation for being fast and fast, was really fast

This theme

AtCoder Beginner Contest B - Trapezoid Sum Difficulty: 27

This theme, the sum of arithmetic progressions

The theme is that if you add normally, it will be TLE, so the formula of the sum of arithmetic progressions

S=n(a+b)/2

Let's use. inject(TLE)

ruby.rb


n = gets.to_i
sum = 0
n.times do
  a, b = gets.split.map(&:to_i)
  sum += (a..b).inject(:+)
end
puts sum

Superbly TLE sum(AC)

ruby.rb


n = gets.to_i
sum = 0
n.times do
  a, b = gets.split.map(&:to_i)
  sum += (a..b).sum
end
puts sum

It passes normally. It seems that sum of range uses the formula of sum of arithmetic progressions internally ~~ (appropriate) ~~ Apparently it was true. Please refer to the comment section.

Ruby(inject) Ruby(sum)
Code length(Byte) 110 103
Execution time(ms) TLE 135
memory(KB) 14344 14392

Summary

Recommended Posts

Ruby sum is a sober and amazing story
What is a Ruby module?
About Ruby product operator (&) and sum operator (|)
What is a Ruby 2D array?
If it is Ruby, it is efficient to make it a method and stock the processing.
A story that separates business logic and model
[Ruby] A program that uses search and each_with_index
A story about a very useful Ruby Struct class
A story about Apache Wicket and atomic design
Ruby and Gem
What is a safety reference operator (&.) Using Ruby ampersand?
What is the difference between a class and a struct? ?? ??
[Ruby] I made a crawler with anemone and nokogiri.
A rough note about Ruby arrays and hash objects
A story I was addicted to before building a Ruby and Rails environment using Ubuntu (20.04.1 LTS)