cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2012 · EasyInteger arithmetic

Average of Even Numbers

National Olympiad — Municipal round (2012 season)

Submission name: average.cpp

Problem summary

Find the arithmetic mean of all even integers in the inclusive interval [m,n].

Input

Two natural numbers m and n.

Output

The mean of the even numbers in the interval.

Constraints

0 < m < n < 2,000,000,000.

Worked example

An independently prepared example for this explanation.

Input

1 6

Output

4

Solution analysis

  1. Move m upward by one if it is odd. Move n downward by one if it is odd. These are the first and last included even numbers.
  2. An arithmetic progression has mean equal to the average of its endpoints: (first+last)/2. Consecutive pairs from opposite ends have this same sum.
  3. In [1,6], the even numbers are 2,4,6. Their mean is (2+6)/2 = 4.

Why it works

Pairing the first and last even numbers, the second and second-last, and so on gives the same sum each time. Consequently the mean is the endpoint average. Since m<n, at least one even integer is present.

Complexity: O(1) time and extra space.

Watch out. Use long long for the endpoint sum, which can exceed signed 32-bit range. The mean is an integer.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
using namespace std;
int main() {
    long long first, last;
    cin >> first >> last;
    // The mean of an arithmetic progression is its endpoint average.
    first += first % 2;
    last -= last % 2;
    cout << (first + last) / 2 << '\n';
}

Source: Arena Olimpiici ↗