The story that sum
, which has a reputation for being fast and fast, was really fast
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 |
Recommended Posts