easy +5 pts

Sum numbers from 1 to n

Write a function that returns the sum of all integers from 1 to n inclusive.

Write a function `sum_to_n(n)` that takes an integer `n` and returns the sum of all integers from 1 to n inclusive. For example, `sum_to_n(5)` returns `1 + 2 + 3 + 4 + 5 = 15`. Assume `n` is a non-negative integer (n >= 0). If `n` is 0, return 0. Use a loop or arithmetic formula.

Constraints

0 <= n <= 1000. The function should handle integers within this range efficiently. Time complexity: O(n) or O(1).

Example

>>> sum_to_n(5)
15
>>> sum_to_n(0)
0
>>> sum_to_n(10)
55
5 points ~5 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Remember to handle the case when n is 0.
You can use a for loop with range(1, n+1).
The arithmetic formula n*(n+1)//2 is also valid.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.