division数论题解

division

题目链接

分类讨论:1.当q∤p时,显然取x=p是最优解。
2.q|p,因为x|p,所以x和q都是将p分解质因数后取一部分相乘得到的,如何保证x不是q的倍数且最大呢?我们用p来缩,当p的任意一个质因数的指数小于q中该质因数的指数,p就不可能是q的倍数了,那么我们可以枚举q的不同质因数,让x中该质因数的指数为q中的-1,其余质因数同p,统计最大即可。(自己举例方便理解)

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int t;
ll a,b,ans;
int get(ll x,ll y)//x里面有几个y 
{
	int cnt=0;
	while(x%y==0)
	{
		x/=y;
		cnt++;
	}
	return cnt;
}
ll Pow(int base,int t)//计算base的t次方 
{
	ll cnt=1;
	for(int i=1;i<=t;i++)cnt*=base;
	return cnt;
}
void update(int f)//更新ans,f为要找的少乘的那个 
{
	ll e=a;
	int c=get(b,f);
	int d=get(a,f);
	e/=Pow(f,d-c+1);//原a除以f的d(原来的个数)-(c-1)(现在的个数)次方
	ans=max(ans,e);
}
int main()
{
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld %lld",&a,&b);
		if(a%b!=0)
		{
			cout<<a<<endl;continue;
		}
		ans=1;
		int s=sqrt(b);
		for(int i=2;i<=s;i++)//枚举q的质因数,让x少乘其中一个,找max 
		{
			if(b%i==0)
			{
				update(i);
				while(!(b%i))b/=i;//避免重复一次性除净i 
			}
		}
		if(b>1)update(b);//可能会有大于根号q的 
		printf("%lld\n",ans);
	}
	return 0;
}
posted @ 2025-02-06 19:33  Crab2016  阅读(39)  评论(0)    收藏  举报