Python BasicsEasy

Sum of N natural numbers

Detailed guide and Python implementation for the 'Sum of N natural numbers' problem.

Problem Statement

Easy

Write a function sum_n_natural(n) that takes a non-negative integer n and returns the sum of the first n natural numbers using the formula n * (n + 1) / 2. If n is 0, return 0.

Constraints
  • 0 <= n <= 10^6

Examples

Example 1
Input
n = 6
Output
21
Explanation

Using the formula: 6 * 7 / 2 = 21.

Example 2
Input
n = 0
Output
0
Explanation

There are no natural numbers to sum, so the result is 0.

Example 3
Input
n = 100
Output
5050
Explanation

100 * 101 / 2 = 5050.

Need a Hint?
Consider using Basics-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.