Sum of a Range

Easy · rating 900 · math

Read two integers a and b with a ≤ b. Print the sum of all integers from a to b inclusive.

Editorial

Sum of a Range adds every integer from a to b inclusive. Looping works, but the arithmetic-series formula gives it in O(1): (a + b) · (b − a + 1) / 2.

print((a + b) * (b - a + 1) // 2)

Complexity

Time: O(1) with the formula. Space: O(1).

Open Sum of a Range in Code Arena →