The Golden Age
Unlucky year in Berland is such a year that its number n can be represented as n = x^a + y^b, 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.
Examples
Input
2 3 1 10
Output
1
Input
3 5 10 22
Output
8
Input
2 3 3 5
Output
0
Note
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 = x^a + y^b, 那么这一年是不幸于 的,现在给定 x 和 y,问你从 年份 L 到年份 R,最长连续幸运多少年。
思路:注意 等式, 是呈指数幂的形式增长的 2 的 60 次方左右,就 大概在 1e18 左右了。所以这道题 可以直接 暴力出 x 的次方到 值为 1e19 左右,y 同理。 然后暴力 求出所有 n, 在挨个判断是否在 L 到 R 中,求最大值即可。
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const ull inf = 1e19;
ull unlucky[5000];
ull powx[70];
ull powy[70];
int main()
{
ull _x,_y,l,r;
powx[0] = 1; powy[0] = 1;
while(~scanf("%I64u%I64u%I64u%I64u",&_x,&_y,&l,&r)){
int x = (int) (log(inf*1.0) / log(_x*1.0));
int y = (int) (log(inf*1.0) / log(_y*1.0));
int p = 0;
for(int i = 1;i <= x;i ++)
powx[i] = powx[i-1] * _x;
for(int i = 1;i <= y;i ++)
powy[i] = powy[i-1] * _y;
//for(int i = 0;i <= x;i ++) printf("%I64u ",powx[i]); printf("\n\n\n");
//for(int i = 0;i <= y;i ++) printf("%I64u ",powy[i]); printf("\n\n\n");
for(int i = 0;i <= x;i ++){
for(int j = 0;j <= y;j ++){
if(powx[i] + powy[j] > r) break;
unlucky[p++] = powx[i] + powy[j];
}
}
sort(unlucky,unlucky + p);
//for(int i = 0;i < p;i ++) printf("%I64u ",unlucky[i]); printf("\n");
int vl = 0,vr = 0; //vl,vr 判断 l 年 和 r 年是否是不幸于的
for(int i = 0;i < p;i ++){
if(unlucky[i] == l)
vl = 1;
else if(unlucky[i] == r)
vr = 1;
}
ll maxx = 0;
int flag = 0;
for(int i = 0;i < p;i ++){
if(flag && unlucky[i] <= r){
maxx = max(maxx,(ll)unlucky[i] - (ll) unlucky[i-1] - 1); // i 和 i-1 下标所对应的年份一点是 unlucky, 所以还要 减一
continue;
}
if(unlucky[i] >= l){
maxx = max(maxx,(ll)unlucky[i] - (ll)l - (ll)vl); //与下同理
flag = 1;
}
}
if(flag) printf("%I64d\n",max(maxx,(ll)r - (ll)unlucky[p-1] - (ll)vr));
else printf("%I64d\n",(ll)r - (ll)l + 1 - (ll)vl - (ll)vr); //没有任何年份在 l 到 r 内,直接算 r - l 即可,但是要判断 l 和 r 是否不幸于
}
return 0;
}