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).
Related problems
- Add Sales Tax — Easy
- Alternating Sum — Easy
- Class Average — Easy
- Floor of Average — Easy
- Keystroke Count — Easy
- Pagination — Easy