Sum of Even Numbers from 1 to N
Solve this ProblemEasy10 min
Topics
BasicsLoopsMath
Companies
TCSInfosysWipro
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.
Test Case 1:
Input:n = 10
Output:30
Explanation:2 + 4 + 6 + 8 + 10 = 30.
Test Case 2:
Input:n = 1
Output:0
Explanation:No even numbers between 1 and 1.
Test Case 3:
Input:n = 4
Output:6
Explanation:2 + 4 = 6.
Constraints
- ◆
0 ≤ n ≤ 1000000
Try the Dry Run
Approach & Solutions
Loop — Check and AddGood
Walk i through every number from 1 to n, adding it to a running total only when it's even. Straightforward, but it still visits every number, even the ones it ends up skipping.
Time
O(n)Space
O(1)Java
1class Solution {
2 public long sumOfEvenNumbers(int n) {
3 long sum = 0;
4 for (int i = 1; i <= n; i++) {
5 if (i % 2 == 0) {
6 sum += i;
7 }
8 }
9 return sum;
10 }
11}Formula — m × (m + 1) Where m = n / 2Optimal
The even numbers up to n are 2, 4, 6, ..., 2m (where m = n / 2, using integer division). Factor a 2 out of each: 2 + 4 + ... + 2m = 2 × (1 + 2 + ... + m). That inner sum is exactly Gauss's formula, m × (m + 1) / 2 — and the 2 outside cancels the /2 inside, leaving simply m × (m + 1).
Time
O(1)Space
O(1)Java
1class Solution {
2 public long sumOfEvenNumbers(int n) {
3 long m = n / 2;
4 return m * (m + 1);
5 }
6}