cppAcademy
FROM LEARNING TO COMPETING

Proficient.
Put your skills to the test.

Bulgarian Informatics Group B · 2009–2026

217 independently explained problems: 54 Municipal, 54 Regional and 109 National. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group B also includes challenging national-level problems. National-round tasks shared by Groups A and B are included. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP B2009 · EasyModular arithmetic

Last Switched Off

National Olympiad — Municipal round (2009 season)

Submission name: last.cpp

Problem summary

Visit regions cyclically starting at 1 and adding a fixed positive step m modulo N. Every region must eventually be visited. Choose the smallest m that makes the given special region appear as late as possible in the first cycle.

Input

N and the special region number s.

Output

The smallest suitable positive step m.

Constraints

1 < N < 1000; 1 ≤ s ≤ N.

Worked example

An independently prepared example for this explanation.

Input

5 4

Output

2

Solution analysis

  1. A step visits all regions exactly when gcd(m,N)=1. Steps with the same residue modulo N have the same order, so it is sufficient to inspect 1 through N−1.
  2. For each valid step simulate the N visits, starting at position 0 (region 1). Record the index at which position s−1 is reached. Maximize that index and keep the first step on ties.
  3. For N=5 and s=4, step 2 visits 1,3,5,2,4. The special region is last, so no step can improve its time, and 2 is the smallest step achieving it.

Why it works

The order generated by addition modulo N has length N/gcd(m,N). Thus exactly the coprime steps are eligible. Enumeration examines every distinct eligible order and compares the exact visit time, selecting the maximum and then its smallest step.

Complexity: O(N²) time and O(1) extra space.

Watch out. This is a fixed cyclic traversal: regions are not removed as in the Josephus problem. Region 1 always appears first.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
#include<numeric>
using namespace std;
int main(){
    // Compute the exact archive answer using the method explained above.
    int n,special;
    cin>>n>>special;
    int answer=1;
    int latest=-1;
    for(int step=1;step<n;step++){
        if(gcd(step,n)!=1){
            continue;
        }
        int position=0;
        for(int time=0;time<n;time++){
            if(position==special-1&&time>latest){
                latest=time;
                answer=step;
            }
            position=(position+step)%n;
        }
    }
    cout<<answer<<'\n';
}

Source: Arena Olimpiici ↗