Python Basics簡単

Sum of N natural numbers

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

問題提起

簡単

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.

制約
  • 0 <= n <= 10^6

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

解決する準備はできましたか?

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

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。