493.Sum of Even Numbers from 1 to N
Easy
Given a non-negative integer
n, return the sum of every even number from 1 up to and including n.
The loopCheck and AddWalking through every number from 1 to n, adding it to a running total only when it's even. version is the direct reading of the problem. The formulam × (m + 1) FormulaFactoring a 2 out of every even term (2+4+...+2m = 2×(1+2+...+m)), then applying Gauss's formula to the inner sum — the 2 outside cancels the /2 inside. version builds directly on Sum of the First N Natural Numbers: every even number up to n is just 2 times a number from 1 to m (where m = n/2), so the whole sum collapses to Gauss's formula in disguise.
Example 1:
Input: n = 10
Output: 30
Example 2:
Input: n = 1
Output: 0
Example 3:
Input: n = 4
Output: 6
+ 3 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ n ≤ 1000000
n =
10