内容中心

2026年靠谱的澳洲移民方案规划费用热门公司推荐-北京澳创移民

To solve this problem, we need to compute the sum of the first n natural numbers. The sum of the first n natural numbers can be efficiently calculated using a mathematical formula instead of iterating through each number, which makes the solution both optimal and concise.

Approach

The sum of the first n natural numbers is given by the formula:
[ \text{Sum} = \frac{n(n+1)}{2} ]
This formula is derived from the observation that the sequence of natural numbers forms an arithmetic series with the first term 1, the last term n, and the number of terms n. The sum of an arithmetic series is the average of the first and last term multiplied by the number of terms.

Solution Code

n = int(input())
print(n * (n + 1) // 2)

Explanation

  1. Reading Input: The input is an integer n which represents the number of natural numbers we want to sum.
  2. Calculation: Using the formula n*(n+1)//2, we compute the sum. The integer division (//) ensures we get an integer result (since the product n*(n+1) is always even).
  3. Output: The result is printed directly.

For example, if the input is 5, the calculation is 5*(5+1)//2 = 5*6//2 = 15, which matches the example output. This approach runs in constant time (O(1)) as it involves a fixed number of arithmetic operations regardless of the value of n.

Answer: The code will output the sum of the first n natural numbers as required. For input 5, the output is 15.

北京澳创移民



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?