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≤10^18; 2≤qi≤10^9) — 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.
题意:
找到一个最大的数x,可以被p整除,不能被q整除。
思路:
如果p%q != 0,直接输出p。
如果p%q = 0,则先记录下q的所有因子,然后用p去整除并,直到整除不了为止,记录当前除后值,最后输出最大的值即可。
ps:我一开始的思路和这个大致相同,但是TLM了,也不知道是哪里TLM了,感觉跟ac的代码好像没啥区别orz,总之还是记一下这个方法。
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
int main()
{
int T;
cin >> T;
while(T--)
{
ll p, q;
cin >> p >> q;
vector<int> v;
if(p % q)
cout << p << endl;
else
{
ll tq = q;
ll tp = p;
for(int i = 2; i <= tq / i; ++i)
{
while(!(tq % i))
{
tq /= i;
v.push_back(i);
}
}
if(tq > 1)
v.push_back(tq);
ll mx = -1;
for(int i = 0; i < v.size(); ++i)
{
tp = p;
while(!(tp % q))
tp /= v[i];
mx = max(tp, mx);
}
cout << mx << endl;
}
}
return 0;
}