easy
0 views
Sum of even numbers from M to N
Calculate the sum of all even numbers within a given range from M to N (inclusive).
Understand the Problem
Problem Statement
Two numbers M and N are passed as the input. The program must print the sum of even numbers from M to N (inclusive of M and N).
Constraints
- 1 ≤ M ≤ 9999999
- M < N ≤ 9999999
- Both M and N are positive integers
- Input values will be within standard integer limits
Examples
Example 1
Input
2
11Output
30Explanation
The even numbers from 2 to 11 are 2, 4, 6, 8, 10. Their sum is 2 + 4 + 6 + 8 + 10 = 30.
Example 2
Input
189
200Output
1170Explanation
The even numbers from 189 to 200 are 190, 192, 194, 196, 198, 200. Their sum is 190 + 192 + 194 + 196 + 198 + 200 = 1170.
Solution
#include <stdio.h>
int main() {
int m, n;
scanf("%d", &m);
scanf("%d", &n);
long long sum = 0;
// Start from first even number >= m
int start = (m % 2 == 0) ? m : m + 1;
// Add all even numbers from start to n
for (int i = start; i <= n; i += 2) {
sum += i;
}
printf("%lld\n", sum);
return 0;
}Time:O((N-M)/2) ≈ O(N-M) - We only iterate through even numbers
Space:O(1) - Only using a constant amount of extra space
Approach:
1. Read M and N from standard input using scanf
2. Initialize sum as long long to handle large results
3. Find the first even number in the range (if M is odd, start from M+1)
4. Loop through even numbers only by incrementing by 2
5. Add each even number to the sum
6. Print the result using printf
Visual Explanation
Loading diagram...