cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2013 · EasyGCD and divisibility

Equal Orange Pieces for All Guests

National Olympiad — Municipal round (2013 season)

Submission name: orange.cpp

Problem summary

Cut each of m identical oranges into the same number of equal pieces, then distribute all pieces equally among n guests. Minimize the pieces cut from each orange.

Input

n guests and m oranges.

Output

The minimum number of pieces per orange.

Constraints

1 ≤ n,m ≤ 10^9.

Worked example

Input and output for the worked example discussed below.

Input

2 5

Output

2

Solution analysis

  1. If every orange is cut into x pieces, there are mx pieces in total. Equal distribution is possible exactly when n divides mx.
  2. Let g=gcd(n,m), n=gn′ and m=gm′. The condition becomes n′ dividing m′x. Since n′ and m′ are coprime, this is equivalent to n′ dividing x. The smallest positive choice is therefore n/g.
  3. For two guests and five oranges, gcd(2,5)=1, so each orange needs two pieces. For two guests and four oranges, the gcd is 2 and x=1: whole oranges can already be shared equally.

Why it works

Reducing by the gcd removes all factors of n already supplied by m. The remaining factor n/g must divide x because it is coprime to m/g. Choosing x=n/g satisfies the condition and no smaller positive x can.

Complexity: O(log min(n,m)) time for Euclid’s gcd algorithm and O(1) auxiliary space.

Watch out. The task asks for pieces per orange, not pieces per person. All oranges use the same cut count. Return 1 when no cutting is needed, not 0.

Commented C++17 solution

An independently written complete program with standard headers.

#include<algorithm>
#include<array>
#include<cmath>
#include<iostream>
#include<limits>
#include<map>
#include<numeric>
#include<set>
#include<string>
#include<vector>
using namespace std;
int main(){
    long long guests;
    long long oranges;
    cin>>guests>>oranges;
    // Only the denominator remaining after gcd reduction must be supplied by cuts.
    cout<<guests/gcd(guests,oranges)<<'\n';
}

Source: Arena Olimpiici ↗