EasyFoundational
Sum of the First N Natural Numbers
- Time limit
- 1 s
- Memory limit
- 128 MB
- Estimated
- 15 min
- Mathematics and Number Theory
Description
Given a non-negative integer n, return the sum of the first n natural numbers, starting from 1.
The required sum is 1 + 2 + ... + n. When n = 0, there are no terms to add, so return 0.
You may use a loop or the arithmetic formula n * (n + 1) / 2. The result is guaranteed to fit within a signed 64-bit integer.
Examples:
n = 5returns15.n = 1returns1.n = 0returns0.
Implement sumNaturalNumbers(n).
Constraints
0 <= n <= 100000000 The result fits within a signed 64-bit integer and within the safe integer range used by the importer.
Sample cases
3Sample 1
Input
n = 5
Expected output
15
Sample 2
Input
n = 1
Expected output
1
Sample 3
Skills and languages
Concepts
- Control Flow and Data Types
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer