easy +5 pts

Sum from 1 to n

Compute the sum of all integers from 1 to n (inclusive) efficiently.

Write a function `sum_1_to_n(n: int) -> int` that returns the sum of all integers from 1 up to and including `n`. For example, `sum_1_to_n(4)` should return `10` because 1 + 2 + 3 + 4 = 10. - The input `n` will be a non-negative integer (`0 <= n <= 10^9`). - For `n = 0`, the sum is `0` (since there are no integers from 1 to 0). - Your solution should handle large values of `n` efficiently. You must not use a loop that iterates from 1 to `n` because that will be too slow for large `n`. - You may use the closed-form formula or any equivalent mathematical approach.

Constraints

0 <= n <= 10^9. The function should run in O(1) time and O(1) space.

Example

>>> sum_1_to_n(1)
1
>>> sum_1_to_n(4)
10
>>> sum_1_to_n(100)
5050
>>> sum_1_to_n(0)
0
5 points ~5 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

The sum 1 + 2 + ... + n can be expressed as n * (n + 1) / 2.
Think about pairing numbers from both ends: 1 with n, 2 with n-1, etc.
Be careful with integer division: the product is always even, so // works.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.