傳送門:Sad powers
分析: 先固定指數p,x^p <= 1e18 可以推導出 x <= 10^(18/p) [取對數推導]
若 p == 2, 則有 10^9 那麼多的數字 滿足條件
若 p >= 3, 則最多有 10^6 的數字滿足 條件
先預處理,把所有不是 完全平方數且滿足 x^p<=1e18(p>=3) 的x都加入到vector, 排序去重
對於每次查詢 輸出 sqrt(R) - sqrt(L-1) + upper_bound(R) - lower_bound(L)
對於快速查詢x的平方根,二分查詢
總的時間複雜度爲 (1e6 + Qlog1e18)
代碼如下:
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
LL root(LL x) {
LL left = 0, right = 1e9;
LL mid ,ans;
while (left<=right) {
mid = (left+right)>>1;
if (mid*mid<=x) {ans = mid; left = mid+1;}
else right = mid-1;
}
return ans;
}
vector<LL>g;
void init(){
g.clear();
for (LL i=2; i<=1e6; i++) {
double t = 1.0*i*i*i;
LL s = i*i*i;
while (t<2e18) {
LL root_s = root(s);
if (root_s*root_s<s) g.push_back(s);
t *= i;
s *= i;
}
}
sort(g.begin(),g.end());
int sz = unique(g.begin(),g.end())-g.begin();
}
int main(){
init();
int q;
scanf("%d",&q);
LL l,r;
while (q--) {
scanf("%I64d %I64d",&l,&r);
int ans1 = upper_bound(g.begin(),g.end(),r) - lower_bound(g.begin(),g.end(),l);
int ans2 = root(r) - root(l-1);
printf("%d\n",ans1+ans2);
}
return 0;
}