Problem Author: | De3b0o |
Prepared by: | De3b0o |
Edited by: | Hasan Saleh (MathModel) |
Solution
Observations:
Any number divisible by x^a can be written as y = k \cdot x^a for some integer k \ge 1.
To maximize majesticness, we want the largest such that there exists some y = k \cdot x^a in the range [l,r].
Once is fixed, the largest possible y \le r is y = \left\lfloor \frac{r}{x^a} \right\rfloor \cdot x^a.
Algorithm:
Iterate over powers of : x^0, x^1, x^2, \dots until x^a > r.
For each power p = x^a, compute the largest multiple that's smaller than :
If y \ge l, update the answer.
Complexity: Each test case performs at most \log_x r iterations, so the total complexity is \mathcal{O}(t \cdot \log r).
#include <bits/stdc++.h>
#define ll long long
using namespace std;
void solve()
{
ll l , r , x;
cin >> l >> r >> x;
ll ans = r;
ll y = x;
while(y<=r)
{
ll rr = (r/y)*y;
if(rr>=l)
ans = (r/y)*y;
y*=x;
}
cout << ans << "\n";
}
int main()
{
ll T=1;
cin >> T;
while(T--)
solve();
}