U

5. Sum of First N Natural Numbers

Easy

Problem Description

Given a non-negative integer NN, calculate the sum of the first NN natural numbers:

S=∑i=1Ni=1+2+⋯+NS = \sum_{i=1}^{N} i = 1 + 2 + \dots + N

If N=0N = 0, the sum is 00.

Input Format

A single line containing an integer NN.

Output Format

Print a single integer representing the sum. Use 64-bit integers to prevent overflow.

Example 1:
Input:
5
Output:
15
Explanation: 1 + 2 + 3 + 4 + 5 = 15.
Example 2:
Input:
0
Output:
0
Explanation: For N = 0, no positive integers are summed, resulting in 0.
Example 3:
Input:
10
Output:
55
Explanation: Using formula N * (N + 1) / 2: 10 * 11 / 2 = 55.
Constraints:
  • 0 <= N <= 10^9
  • Time complexity target: O(1)
  • Auxiliary space target: O(1)
Follow up:How would you compute the sum of squares 1^2 + 2^2 + ... + N^2 in O(1) time?
1,180 Online