|
U
Pro5. Sum of First N Natural Numbers
Easy
Problem Description
Given a non-negative integer N, calculate the sum of the first N natural numbers:
S=i=1∑Ni=1+2+⋯+N
If N=0, the sum is 0.
Input Format
A single line containing an integer N.
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^9Time 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
Code
|Loading Code Editor...
SavedLn 1, Col 1
input =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit