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
11
Output
35
Explanation

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
111
Output
2407
Explanation

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:

  1. Variable Declaration: We declare M and N as int to store the input range, and sum as long long to handle potentially large sums (up to ~10^13)
  2. Input Reading: Use scanf to read the two integers from standard input
  3. Loop and Check: Iterate from M to N (inclusive). For each number, check if it's odd using i % 2 == 1
  4. Sum Calculation: If the number is odd, add it to the running sum
  5. Output: Print the final sum using printf with %lld format specifier for long long

Visual Explanation

Loading diagram...