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 E2011 · EasyInverse operations

I Thought of a Number

Autumn Tournament (2011)

Submission name: think.cpp

Problem summary

Bobi chooses a number. He divides it by a and subtracts a, then repeats those same two operations on the result, obtaining b. Recover the original number.

Input

Two integers a and b.

Output

The original number.

Constraints

1 ≤ a, b ≤ 100.

Worked example

Original statement sample, translated without changing its numeric data.

Input

7 33

Output

2009

Solution analysis

  1. Work backward from the final result b. The inverse of subtracting a is adding a; the inverse of dividing by a is multiplying by a.
  2. Undo one full round with (value + a) × a, and apply that inverse twice. int is sufficient: the maximum answer is 2,010,000.
  3. For a = 7 and b = 33, the previous value is (33 + 7) × 7 = 280. The original value is (280 + 7) × 7 = 2009.

Why it works

For any value x, applying the forward round to (x + a)a yields ((x + a)a)/a − a = x. Thus each inverse round exactly undoes one forward round. Applying it twice recovers the original number.

Complexity: O(1) time and O(1) extra space: the input has a fixed number of values.

Watch out. Undo the operations in reverse order. The repeated action includes both division and subtraction.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
using namespace std;
int main(){
    int a,b;
    cin>>a>>b;
    int value=b;
    for(int round=0;round<2;round++){
        // Undo subtraction first, then division.
        value=(value+a)*a;
    }
    cout<<value<<'\n';
}

Source: Arena Olimpiici ↗