Codeforces Round #680 C. Division (decomposition of prime factors)

C. Division

Title Portal:

Division

Main idea:

Given two integers p and q, find the largest x such that p%x==0&&x%q! = 0.

Ideas:

First classify and discuss:
1. If p%q != 0, then obviously x=p

2. If p=q, then find the smallest prime factor k of p, x=p/k

3.p%q=0&&p!=q.
p%q=0 means that after q decomposes prime factors, each prime factor must exist in p and the number of each prime factor in q must be less than or equal to the number of this prime factor in p. Then we enumerate the prime factors in q, record the number of prime factors ai in q as num1, and record the number of prime factors ai in p as num2, then find the smallest pow( ai, num2-num1+1) , Recorded as minn. Then x=p/minn.

AC Code

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e9;
int t;
LL p,q;
LL quick_pow(LL a,LL b)
{
    
    
    LL res=1;
    while(b)
    {
    
    
        if(b%2) res=res*a;
        b=b/2;
        a=a*a;
    }
    return res;
}
int main()
{
    
    
    scanf("%d",&t);
    while(t--)
    {
    
    
        scanf("%lld%lld",&p,&q);
        if(p%q!=0) printf("%lld\n",p);
        else
        {
    
    
            if(p==q)
            {
    
    
                int idx=0;
                for(int i=2;i*i<=p;i++)
                {
    
    
                    if(p%i==0)
                    {
    
    
                        idx=i;
                        break;
                    } 
                }
                if(idx==0) printf("1\n");
                else printf("%lld\n",p/idx);
            }
            else
            {
    
    
                LL k=p;
                LL res=1e18;
                LL idx=2;
                while(idx*idx<=q)
                {
    
    
                    if(q%idx!=0)
                    {
    
    
                        idx++;
                        continue;
                    }
                    LL cnt1=0,cnt2=0;
                    while(q%idx==0)
                    {
    
    
                        q=q/idx;
                        cnt2++;
                    }
                    while(p%idx==0)
                    {
    
    
                        p=p/idx;
                        cnt1++;
                    }
                    res=min(res,quick_pow(idx,cnt1-cnt2+1));
                    idx++;
                }
                if(q>1)
                {
    
    
                    LL cnt2=1,cnt1=0;
                    while(p%q==0)
                    {
    
    
                        cnt1++;
                        p=p/q;
                    }
                    res=min(res,quick_pow(q,cnt1-cnt2+1));
                }
                printf("%lld\n",k/res);
            }
        }
    }
    //system("pause");
    return 0;
}

Guess you like

Origin blog.csdn.net/Stevenwuxu/article/details/109474068