cppAcademy
FROM LEARNING TO COMPETING

Real problems.
Your next challenge.

Explore the Group C Olympiad archive.
Choose a topic. Find a challenge. Build your solution.

213 tasks across the Municipal, Regional, and National rounds (2009–2026), plus 4 previously featured problems. 146 tasks have independently written English summaries, analyses, and C++17 solutions; the remaining entries link to Arena. Topic tags are from Arena or our reviewed explanations. Difficulty labels are learning estimates, not official ratings.
GROUP C2016 · MediumInteger Powers

All perfect-power representations

National Olympiad — Municipal round

Submission name: stepen.cpp

Problem summary

Find every representation X=a^b with positive integer base a and integer exponent b>1.

Input

X.

Output

First the number of representations; then base and exponent pairs, sorted by decreasing base.

Constraints

2 ≤ X ≤ 10^9.

Worked example

An independently prepared example for this explanation.

Input

64

Output

3
8 2
4 3
2 6

Solution analysis

  1. Try exponents 2 through 29: larger exponents with base≥2 exceed the bound.
  2. For each exponent binary-search its integral root. Compare powers using bounded multiplication instead of floating-point rounding.
  3. Keep exact roots and sort by decreasing base.

Why it works

Every valid exponent lies in the checked range and powers strictly increase with positive base. Exact root search finds precisely all representations.

Complexity: O(log² X · log X) elementary multiplications (at most 29·30·29 here); O(log X) space.

Watch out. Avoid floating-point root equality and overflow when testing powers.

Commented C++17 solution

An independently written complete program with standard headers.

// Key idea: Every valid exponent lies in the checked range and powers strictly increase with positive
// base. Exact root search finds precisely all representations.
#include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
using namespace std;
int main(){
    long long x;
    cin>>x;
    vector<pair<long long,int>>ans;
    for(int b=2;b<=29;b++){
        long long lo=2,hi=x;
        while(lo<=hi){
            long long a=(lo+hi)/2,p=1;
            for(int j=0;j<b;j++){
                if(p>x/a){
                    p=x+1;
                    break;
                }
                p*=a;
            }
            if(p==x){
                ans.push_back({a,b});
                break;
            }
            if(p<x){
                lo=a+1;
            }
            else{
                hi=a-1;
            }
        }
    }
    sort(ans.rbegin(),ans.rend());
    cout<<ans.size()<<'\n';
    for(auto[a,b]:ans){
        cout<<a<<' '<<b<<'\n';
    }
}

Source: Arena Olimpiici ↗