C - Division
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 tt pairs of integers p_ipi and q_iqi and for each pair decided to find the greatest integer x_ixi, 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 tt (1≤t≤50) — the number of pairs.
Each of the following tt lines contains two integers pi and qi (1 ≤ pi ≤ 1e18; 2 ≤ qi ≤ 1e9) — the i-th pair of integers.
Output
Print tt 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 x_ixi satisfying the divisibility conditions for the given constraints.
Sample 1
Inputcopy Outputcopy 3 10 4 12 6 179 822 10 4 179Note
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 p_2 = 12p2=12 and q_2 = 6q2=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.
Sponsor
分两种情况:
1:p不是q的倍数,这种情况最大的x必然是p
2:p是q的倍数:
这时候,p和q共有的是q以及它的因子,要想合理的缩小p的范围来使p%q!=0,只要用q的因子整除p,直到p%q!=0就可以了,这样得到的x(p不断除以q的因子),由于除的缘故,必然是p的倍数且不是q的倍数(模!=0)
于是就可以:1:先用p除以p和q最大的共有数q,得到一个x,存到最大值里;这一步不是是必要的,下面代码会展示两种写法(其实想想就知道了)
2:再用p除以q的各个因子,得到x,与最大值比较并存入
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll t, p, q, mymax;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> t;
while (t--) {
cin >> p >> q;
if (p % q) {//如果p不是q的倍数(包括p<q),那么最大的x就是p
cout << p << endl;
}
else {
mymax = -1;//初始化
ll low = p;
while (low % q == 0) {//如果p是q的倍数的话,去除p中所有等于q的因子,直到p不是q的倍数
low /= q;
}
mymax = max(mymax, low);
for (ll i = 2;/*i = 1 第二种写法*/ i * i <= q; i++) {//找q的因子,这样不用开方
if (q % i == 0) {//如果是因子
ll low1 = p, low2 = p, lowq = q / i;
//因子成对,所以每个因子有两种情况
while (low1 % q == 0 /* && i != 1 */ ) {//当p包含q时,从p中慢慢去除q的因子,直到p不是q的倍数
low1 /= i;
}
/*if (i != 1)*/ mymax = max(mymax, low1);
while (low2 % q == 0) {//同理,这是第二种情况
low2 /= lowq;
}
mymax = max(mymax, low2);//要求最great的x
}
}
cout << mymax << endl;
}
}
return 0;
}