HDOJ 题目4497 GCD and LCM (组合数学,gcd性质)

来源:互联网 发布:网络代售许可证 编辑:程序博客网 时间:2024/06/05 01:51

GCD and LCM

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 950    Accepted Submission(s): 443


Problem Description
Given two positive integers G and L, could you tell me how many solutions of (x, y, z) there are, satisfying that gcd(x, y, z) = G and lcm(x, y, z) = L?
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.
 

Input
First line comes an integer T (T <= 12), telling the number of test cases.
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.
 

Output
For each test case, print one line with the number of solutions satisfying the conditions above.
 

Sample Input
2 6 72 7 33
 

Sample Output
72 0
 

Source
2013 ACM-ICPC吉林通化全国邀请赛——题目重现
 

Recommend
liuyiding   |   We have carefully selected several similar problems for you:  4959 4958 4957 4956 4955 
 思路:http://blog.csdn.net/synapse7/article/details/13009253

解释下这里的6是怎么来的:

设L/G=(p1^r1)*(p2^r2)*(p3^r3)…(pm^rm)

又设

x=(p1^i1)*(p2^i2)*(p3^i3)…(pm^im)

y=(p1^j1)*(p2^j2)*(p3^j3)…(pm^jm)

z=(p1^k1)*(p2^k2)*(p3^k3)…(pm^km)

对于某个r,i、j、k里面一定有一个是r,并且一定有一个是0,所以i,j,k有一下3种情况:

r 0 0 ,有C(3,1)种
r 0 r ,有C(3,1)种
r 0 1~r-1 ,有(r-1)*A(3,3)种

所以一共是6*r种。

我的ac代码

#include<stdio.h>int main(){int t;scanf("%d",&t);while(t--){int n,m,i,sum,ans=1;scanf("%d%d",&m,&n);if(n%m){printf("0\n");continue;}n/=m;for(i=2;i<=n;i++)//数字不是很大,没必要打素数表,直接枚举就好{if(n%i==0){sum=0;while(!(n%i)){sum++;n/=i;}ans*=6*sum;}}//if(n>1)ans*=6;printf("%d\n",ans);}}


比较巧妙地一种写法,收藏一下

/*15ms,200KB*/#include<cstdio>int main(){int t;long long m, n, ans, i, count;scanf("%d", &t);while (t--){scanf("%I64d%I64d", &m, &n);if (n % m) puts("0");///注意特判else{n /= m;ans = 1;for (i = 2; i * i <= n; i += 2)///不用求素数,因为范围很小(注意n在不断减小){if (n % i == 0){count = 0;while (n % i == 0){n /= i;++count;}ans *= 6 * count;}if (i == 2)--i;///小技巧}if (n > 1) ans *= 6;printf("%I64d\n", ans);}}return 0;}



 

0 0