codeforces#680 C. Division

time limit per test1 second
memory limit per test512 megabytes
inputstandard input
outputstandard output
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
inputCopy
3
10 4
12 6
179 822
outputCopy
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.
思路:
q<p和q%p!=0这两种情况显然答案就是q本身。
看q%p==0的情况:

为了保证q%x==0,x%p!=0,那么
把q的每个因子去除p,直到p不等于q,这就是一个答案,把每个因子的答案都求出来取最大值,就是答案了。
思路没错,只是第一次交时超时了,优化了下找因子的过程和删了点无用的代码就好了。
代码:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
 int t;
 cin>>t;
 while(t--){
 ll p,q;
 scanf("%lld%lld",&p,&q);
 if(p%q!=0)cout<<p<<endl;
 else{
 ll  maxx=1;
 for(ll i=2;i*i<=q;i++){
  if(q%i==0){
  ll temp=p;
  while(temp%q==0){
   temp/=i;
  }
  ll temp2=p,num=q/i;
  while(temp2%q==0){
   temp2/=num;
  }
  maxx=max(temp,maxx);
  maxx=max(temp2,maxx); 
  }
 }
 ll temp=p;
 while(temp%q==0)temp/=q;
 maxx=max(maxx,temp);
 cout<<maxx<<endl;
}
}
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值