GCD and LCM
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 2039 Accepted Submission(s): 910
Note, gcd(x, y, z) means the greatest common divisor of x, y and z, while lcm(x, y, z) means the least common multiple of x, y and z.
Note 2, (1, 2, 3) and (1, 3, 2) are two different solutions.
The next T lines, each contains two positive 32-bit signed integers, G and L.
It’s guaranteed that each answer will fit in a 32-bit signed integer.
2 6 72 7 33
72 0
思路:
首先我们可以写出GCD(x,y,z)和LCM(x,y,z)的公式
我们知道任意一个数x可以拆分成x=p1^e1*p2^e2...pk^ek(pi是因质数)
而且GCD(x,y,z)=p1^(min(xe1,ye1,ze1))*p2^(min(xe2,ye2,ze2))...pk^(min(xek,yek,zek))
LCM(x,y,z)=p1^(max(xe1,ye1,ze1))*p2^(max(xe2,ye2,ze2))...pk^(max(xek,yek,zek))
GCD与LCM质因数可以相同,只不过有些质因数的指数为0.
那么对于给定的G和L,我们可以求得每一个质因数的三个指数中的最小值和最大值
比如G=p1^e1*p2^e2...pk^ek L=p1^w1*p2^w2...pk^wk
假设q是第三个指数,那么有min(ei,qi,wi)=ei, max(ei,qi,wi)=wi
而且qi的值必须在[ei,wi]之间,我们分情况讨论一共会有几种情况
1.qi的值不等于ei或者wi,那么qi是(ei,wi),一共有wi-ei-1种选择,而且题目中说了相同数字顺序不同算不同情况,所以对于三个互不相同的数字,一共有A(3,3)中情况
也就是说这里ans=6*(wi-ei-1)
2.qi的值等于ei或者wi,那么qi一共有两种选择,且对于给定的三个数字里有两个相同数字的排列方式,一共有A(3,1)种
也就是说这里ans=3*2
两种情况加起来ans=6*(wi-ei) 再根据乘法原理,把所有质因数的6*(wi-ei)相乘即可得到结果
注意这里如果wi==ei,也就说只能三个数都一样,此时不能运用公式,因为一旦相乘的数中出现了0,结果必然会是0 此时直接乘以1就可以。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 100000
#define LL long long
LL d[N][2],e[N][2],cntn,cntm;
void devide(int n,int m)
{
cntn=cntm=0;
for(int i=2; i*i<=n; i++)
{
if(n%i==0)
{
int num=0;
while(n%i==0)
{
num++;
n/=i;
}
d[++cntn][0]=i,d[cntn][1]=num;
}
}
for(int i=2; i*i<=m; i++)
{
if(m%i==0)
{
int num=0;
while(m%i==0)
{
num++;
m/=i;
}
e[++cntm][0]=i,e[cntm][1]=num;
}
}
if(n>1) d[++cntn][0]=n,d[cntn][1]=1;
if(m>1) e[++cntm][0]=m,e[cntm][1]=1;
}
LL solve(int n,int m)
{
if(m%n!=0) return 0;
devide(n,m);
LL ans=1,v;
for(int i=1; i<=cntm; i++)
{
int flag=0;
for(int j=1; j<=cntn; j++)
if(e[i][0]==d[j][0])
{
flag=1;
v=j;
break;
}
if(!flag) ans=ans*6*e[i][1];
else
{
LL t=e[i][1]-d[v][1];
if(t==0) continue;
ans=ans*6*t;
}
}
return ans;
}
int main()
{
int T;
int n,m;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&n,&m);
LL ans=solve(n,m);
printf("%lld\n",ans);
}
return 0;
}