492.Sum of the First N Natural Numbers
Easy
Given a non-negative integer
n, return the sum 1 + 2 + 3 + ... + n.
The loopAddition LoopWalking i from 1 to n, adding each value to a running total. version is the direct reading of what "sum of the first n numbers" means. Gauss's formulaGauss's Formulan × (n + 1) / 2 — pairing the smallest and largest remaining numbers (1 with n, 2 with n-1, ...), each pair summing to n+1, with n/2 such pairs., famously discovered by Carl Friedrich Gauss as a schoolboy, skips the loop entirely: it's one multiplication and one division, no matter how large n is — a genuine O(1) solution to an O(n)-looking problem.
Example 1:
Input: n = 5
Output: 15
Example 2:
Input: n = 1
Output: 1
Example 3:
Input: n = 0
Output: 0
+ 3 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ n ≤ 1000000
n =
5