题意:
找一个最大的数X,使p%x==0且x%q!=0,题目保证至少有一个答案满足题意。
题目:
Oleg’s favorite subjects are History and Math, and his favorite branch of mathematics is division.
To improve his division skills, Oleg came up with t pairs of integers pi and qi and for each pair decided to find the greatest integer xi, such that:
pi is divisible by xi;
xi is not divisible by qi.
Oleg is really good at division and managed to find all the answers quickly, how about you?
Input
The first line contains an integer t (1≤t≤50) — the number of pairs.
Each of the following t lines contains two integers pi and qi (1≤pi≤1018; 2≤qi≤109) — the i-th pair of integers.
Output
Print t integers: the i-th integer is the largest xi such that pi is divisible by xi, but xi is not divisible by qi.
One can show that there is always at least one value of xi satisfying the divisibility conditions for the given constraints.
Example
Input
3
10 4
12 6
179 822
Output
10
4
179
Note
For the first pair, where p1=10 and q1=4, the answer is x1=10, since it is the greatest divisor of 10 and 10 is not divisible by 4.
For the second pair, where p2=12 and q2=6, note that
12 is not a valid x2, since 12 is divisible by q2=6;
6 is not valid x2 as well: 6 is also divisible by q2=6.
The next available divisor of p2=12 is 4, which is the answer, since 4 is not divisible by 6.
分析:
1.先说当题目至少满足一个X,使之满足条件,分析可得,这个值为1,需要特判;
2.我在大犇博客借鉴的,嘻嘻:
显然,当 p与q不满足整除关系(p%q != 0) 时,最大的x就是p本身,这个简单。
但是当 p % q == 0 时怎么办呢?
不难发现,当 p % q == 0 时,
我们令 q = A * B ,
则 p = An * Bn * C , 其中C是一个与A,B均不满足整除关系的整数。
那么,从每一个 x = p / An 中找到的x(max)不就是结果了吗?
显然,A、B的集合就是q的所有因子,我们只需要O(sqrt(n))的时间来找出它们。
对于An,我们只需要让p不断的除以因子A直到p不再能被q整除就行了。
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,m,t,ans;
ll solve(int x){
if(x==1) return x;
ll num=n;
while(num%m==0)
num/=x;
return num;
}
void dfs(ll x){
for(int i=1;i*i<=x;i++){
if(x%i==0){
int a=i,b=x/i;
ans=max(ans,solve(a));
ans=max(ans,solve(b));
}
}
}
int main(){
cin>>t;
while(t--){
ans=0;
cin>>n>>m;
dfs(m);
if(ans!=0)
cout<<ans<<endl;
else cout<<"1"<<endl;
}
return 0;
}