Division CodeForces - 1445C(数论因子相关)
題意:
找一個(gè)最大的數(shù)X,使p%x==0且x%q!=0,題目保證至少有一個(gè)答案滿足題意。
題目:
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
Input
3
10 4
12 6
179 822
Output
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.
The next available divisor of p2=12 is 4, which is the answer, since 4 is not divisible by 6.
分析:
1.先說(shuō)當(dāng)題目至少滿足一個(gè)X,使之滿足條件,分析可得,這個(gè)值為1,需要特判;
2.我在大犇博客借鑒的,嘻嘻:
顯然,當(dāng) p與q不滿足整除關(guān)系(p%q != 0) 時(shí),最大的x就是p本身,這個(gè)簡(jiǎn)單。
但是當(dāng) p % q == 0 時(shí)怎么辦呢?
不難發(fā)現(xiàn),當(dāng) p % q == 0 時(shí),
我們令 q = A * B ,
則 p = An * Bn * C , 其中C是一個(gè)與A,B均不滿足整除關(guān)系的整數(shù)。
那么,從每一個(gè) x = p / An 中找到的x(max)不就是結(jié)果了嗎?
顯然,A、B的集合就是q的所有因子,我們只需要O(sqrt(n))的時(shí)間來(lái)找出它們。
對(duì)于An,我們只需要讓p不斷的除以因子A直到p不再能被q整除就行了。
AC代碼:
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n,m,t,ans; ll solve(int x){if(x==1) return x;ll num=n;while(num%m==0)num/=x;return num; } void dfs(ll x){for(int i=1;i*i<=x;i++){if(x%i==0){int a=i,b=x/i;ans=max(ans,solve(a));ans=max(ans,solve(b));}} } int main(){cin>>t;while(t--){ans=0;cin>>n>>m;dfs(m);if(ans!=0)cout<<ans<<endl;else cout<<"1"<<endl;}return 0; }總結(jié)
以上是生活随笔為你收集整理的Division CodeForces - 1445C(数论因子相关)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 团体程序设计天梯赛-练习集L1-025
- 下一篇: Divide and Sum CodeF