C. Division(思维+质因数分解)

https://codeforces.com/contest/1445/problem/C


To improve his division skills, Oleg came up with tt pairs of integers pipi and qiqi and for each pair decided to find the greatest integer xi, such that:

  • pi is divisible by xi;
  • xi is not divisible by qi.

pi and qi (1≤pi≤1e18; 2≤qi≤1e9)


思路:从质因数分解的角度出发,那么可以发现,如果两个数不能整除,直接就是pi.

如果能整除,那么他们的质因子种类都是同的。只不过质因数的次幂不同。那么我们只要让pi其一个质因子次幂降到qi的对应质因子次幂的少一个就能满足不整除。至于选哪一个枚举即可。

(由于时间复杂度把不断整除算成了sqrt(n)导致卡了好久-.-)

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5;
typedef long long LL;
LL qpow(LL a,LL n)
{
	LL ans=1;
	while(n)
	{
		if(n&1) ans*=a;
		a*=a;
		n>>=1;
	}
	return ans;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL t;cin>>t;
  while(t--){
    LL p,q;cin>>p>>q;
    if(p%q!=0){
        cout<<p<<endl;
    }
    else{
    LL x=p;
    LL ans=0x3f3f3f3f3f3f3f3f;
	for(LL i=2;i*i<=q;i++)
	{
		if(q%i) continue;
		LL c1=0,c2=0;
		while(q%i==0)
		{
			c1++;
			q/=i;
		}
		while(p%i==0)
		{
			c2++;
			p/=i;
		}
		ans=min(ans,qpow(i,c2-c1+1));
	}
	if(q>1)
	{
		LL i=q;
		LL c1=0,c2=0;
		while(q%i==0)
		{
			c1++;
			q/=i;
		}
		while(p%i==0)
		{
			c2++;
			p/=i;
		}
		ans=min(ans,qpow(i,c2-c1+1));
        }
        cout<<x/ans<<endl;
    }

  }
return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/112981973