
Problem
Solution
Submissions
Sum of All Even Numbers
Certification: Basic Level
Accuracy: 100%
Submissions: 5
Points: 5
Write a C++ program to compute the sum of even numbers in the range [1, n].
Example 1
- Input: n = 10
- Output: 30
- Explanation:
- Step 1: Identify the even numbers in the range [1, 10]: 2, 4, 6, 8, 10
- Step 2: Calculate the sum of these even numbers: 2 + 4 + 6 + 8 + 10 = 30
- Step 3: Return the sum: 30
Example 2
- Input: n = 15
- Output: 56
- Explanation:
- Step 1: Identify the even numbers in the range [1, 15]: 2, 4, 6, 8, 10, 12, 14
- Step 2: Calculate the sum of these even numbers: 2 + 4 + 6 + 8 + 10 + 12 + 14 = 56
- Step 3: Return the sum: 56
Constraints
- 1 ≤ n ≤ 10^6
- Note: You can optimize using the formula: sum of first k even numbers = k(k+1)
- Time Complexity: O(1) when using the formula, O(n) for iterative approach
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use arithmetic series formula: k * (k + 1) where k = n//2
- Iterate with step size 2 for optimization
- Return 0 if n < 2