easy
0 views
Sum of odd numbers from M to N
Calculate the sum of all odd numbers in a given range [M, N] inclusive.
Understand the Problem
Problem Statement
Two numbers M and N are passed as the input. The program must print the sum of odd numbers from M to N (inclusive of M and N).
Constraints
- 1 <= M <= 9999999
- M < N <= 9999999
- The range must include at least two numbers (M < N)
Examples
Example 1
Input
2
11Output
35Explanation
The odd numbers from 2 to 11 are 3, 5, 7, 9, 11. Their sum is 3 + 5 + 7 + 9 + 11 = 35.
Example 2
Input
55
111Output
2407Explanation
The odd numbers from 55 to 111 inclusive are: 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111. Their sum is 2407.
Solution
#include <stdio.h>
int main() {
int M, N;
long long sum = 0;
// Read input values
scanf("%d", &M);
scanf("%d", &N);
// Iterate through the range and sum odd numbers
for (int i = M; i <= N; i++) {
if (i % 2 == 1) {
sum += i;
}
}
// Output the result
printf("%lld\n", sum);
return 0;
}Time:O(N - M + 1) - We iterate through all numbers in the range once
Space:O(1) - We only use a constant amount of extra space
Approach:
C Solution Explanation:
- Variable Declaration: We declare
MandNasintto store the input range, andsumaslong longto handle potentially large sums (up to ~10^13) - Input Reading: Use
scanfto read the two integers from standard input - Loop and Check: Iterate from
MtoN(inclusive). For each number, check if it's odd usingi % 2 == 1 - Sum Calculation: If the number is odd, add it to the running sum
- Output: Print the final sum using
printfwith%lldformat specifier forlong long
Visual Explanation
Loading diagram...