Y sequence
Problem Description
Yellowstar likes integers so much that he listed all positive integers in ascending order,but he hates those numbers which can be written as a^b (a, b are positive integers,2<=b<=r),so he removed them all.Yellowstar calls the sequence that formed by the rest integers“Y sequence”.When r=3,The first few items of it are:
2,3,5,6,7,10......
Given positive integers n and r,you should output Y(n)(the n-th number of Y sequence.It is obvious that Y(1)=2 whatever r is).
2,3,5,6,7,10......
Given positive integers n and r,you should output Y(n)(the n-th number of Y sequence.It is obvious that Y(1)=2 whatever r is).
Input
The first line of the input contains a single number T:the number of test cases.
Then T cases follow, each contains two positive integer n and r described above.
n<=2*10^18,2<=r<=62,T<=30000.
Then T cases follow, each contains two positive integer n and r described above.
n<=2*10^18,2<=r<=62,T<=30000.
Output
For each case,output Y(n).
Sample Input
2 10 2 10 3
Sample Output
13 14
题意:给定正整数n和r,定义Y数列为从正整数序列中删除所有能表示成a^b(2 ≤ b ≤ r)的数后的数列,求Y数列的第n个数是多少。例如n = 10, r = 3,则Y数列为2 3 5 6 7 10 11 12 13 14,第10个数是14。
思路:首先我们知道,小于n的平方数有sqrt(n)即pow(n+0.5, 1.0/2)个,立方数有pow(n+0.5, 1.0/3)个.....同理递推。(n+0.5是为了确保精度)
值得注意的是,当b是合数时例如b=6时,因为a^6 = (a^3)^2 = (a^2)^3,要求Y序列中第n个数是什么,直接求似乎有点难,我们这样想,先求n前面能表示成平方数、立方数...r方数的有多少个,假设为tmp,再让n+tmp(相当于前面筛掉了tmp个数
),再依次迭代,直到新加的tmp里面没有能表示成2~r方的数即可,因为能表示成幂指数的数越往后越稀疏,所以这样复杂度就比直接二分低了,但是正如前面所说的,我们筛掉平方数时筛掉了6次方数但是晒立方数时又筛掉了6次方数,所以要用容斥来维护。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int p[30];
ll n, r;
vector<int> Exclu;
void getPrime() {
bool vis[70];
int pos = 0;
memset(vis, 0, sizeof(vis));
for(int i = 2; i < 70; ++i) {
if(!vis[i]) {
p[pos++] = -i;
}
for(int j = i; j < 70; j += i) {
vis[j] = 1;
}
}
}
void init() {
Exclu.clear();
for(int i = 0; abs(p[i]) <= r; ++i) {
int cnt = Exclu.size();
for(int j = 0; j < cnt; ++j) {
if(abs(p[i] * Exclu[j]) <= 63) {
Exclu.push_back(p[i] * Exclu[j]);
}
}
Exclu.push_back(p[i]);
}
}
ll getNum(ll n) {
if(n == 1) return 0;
ll ans = n;
for(int k : Exclu) {
// +0.5为了保证精度;-1是暂时不包含1(因为当a=1时,a^b一定会等于1)
ll tmp = (ll)pow(n + 0.5, 1.0/abs(k)) - 1;
if(k < 0) {
ans -= tmp;
}
else {
ans += tmp;
}
}
// 减去刚才没有包含在内的1
return ans - 1;
}
int main()
{
ios::sync_with_stdio(false);
int T;
getPrime();
cin >> T;
ll ans, tmp;
while(T--) {
cin >> n >> r;
init();
ans = n;
while(true) {
tmp = getNum(ans);
if(tmp == n)
break;
ans += n - tmp;
}
cout << ans << endl;
}
return 0;
}