Unlucky year in Berland is such a year that its number n can be represented as n = xa + yb, where a and b are non-negative integer numbers.
For example, if x = 2 and y = 3 then the years 4 and 17 are unlucky (4 = 20 + 31, 17 = 23 + 32 = 24 + 30) and year 18 isn't unlucky as there is no such representation for it.
Such interval of years that there are no unlucky years in it is called The Golden Age.
You should write a program which will find maximum length of The Golden Age which starts no earlier than the year l and ends no later than the year r. If all years in the interval [l, r] are unlucky then the answer is 0.
Input
The first line contains four integer numbers x, y, l and r (2 ≤ x, y ≤ 1018, 1 ≤ l ≤ r ≤ 1018).
Output
Print the maximum length of The Golden Age within the interval [l, r].
If all years in the interval [l, r] are unlucky then print 0.
Sample 1
Inputcopy Outputcopy 2 3 1 10 1Sample 2
Inputcopy Outputcopy 3 5 10 22 8Sample 3
Inputcopy Outputcopy 2 3 3 5 0Note
In the first example the unlucky years are 2, 3, 4, 5, 7, 9 and 10. So maximum length of The Golden Age is achived in the intervals [1, 1], [6, 6] and [8, 8].
In the second example the longest Golden Age is the interval [15, 22].
题目大意:伯兰的不幸年份是这样的年份,其数字n可以表示为n = xa + yb,其中a和b是非负整数。
例如,如果 x = 2 且 y = 3,则 4 年和 17 年是不吉利的(4 = 20 + 31,17 = 23 + 32 = 24 + 30),而第 18 年并不不幸,因为它没有这样的表示。
你应该写一个程序,它将找到黄金时代的最大长度,它不早于年份l开始,不晚于年份r结束。如果区间 [l, r] 中的所有年份都不走运,则答案为 0。
#pragma GCC optimize(2)
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define endl '\n'
ll x, y, l, r;
vector<ll> creatarr(ll power) {
vector<ll> t;
t.push_back(1);
ll low = power;
while (r / power >= t.back()) {
t.push_back(low);
low *= power;
}
return t;
}
int main(){
ios::sync_with_stdio(false); cin.tie(nullptr);
cin >> x >> y >> l >> r;
ll sum = 0;
//求所有小于右边界的指数可能(指数级增长不管左边界对速度影响不大(管了也不快))
vector<ll>a(creatarr(x));
vector<ll>b(creatarr(y));
vector<ll>year;
for (int i = 0; i < a.size(); ++i) {//暴力找符合条件的指数组
for (int j = 0; j < b.size(); ++j) {
if (a[i] + b[j] >= l && a[i] + b[j] <= r) {
year.push_back(a[i] + b[j]);
}
}
}
sort(year.begin(), year.end());
ll ans=0;
if(year.size()>0) //处理两端
ans=max(year.front()-l,r-year.back());
else
ans=r-l+1;
for(int i=0;i<year.size();i++){
ans=max(year[i]-l-1,ans);
l=year[i];
}
cout<<ans;
return 0;
}