zoj 1577 (gcd,lcm)求 所有的对数。

来源:互联网 发布:mac虚拟机不能上网 编辑:程序博客网 时间:2024/05/18 13:26

Given x and y (2 <= x <= 100,000, 2 <= y <= 1,000,000), you are to count the number of p and q such that:

1) p and q are positive integers;

2) GCD(p, q) = x;

3) LCM(p, q) = y.

Input
x and y, one line for each test.

Output
Number of pairs of p and q.

Sample Input
3 60

Sample Output
4

给你 x,y。gcd和lcm 问这样的对数有多少。

转载:http://blog.csdn.net/xieshimao/article/details/6439803

先说说解法吧。
假设g=gcd(p,q),l=lcm(p,q),key=l/g

我们可以想象一下:
那个key是什么?想清楚这个问题就很简单了。
l是p和q公共的素因子的并集,而g则是交集(仔细理解这句话!!)
于是key的意思就是l刚好比g多的一部分素因子
于是我们可以选择这些素因子和g组合得到了p
另一部分和g组合得到了q

假设key的素因子个数(重复的不算)有n个
那么选择方案就有:C(n,0)+C(n,1)+C(n,2)+…+C(n,n)
熟悉组合学公式的童鞋肯定很快就可以反应过来
上面那个式子的和为2^n,所以剩下的工作就非常的简单了

#include <bits/stdc++.h>using namespace std;vector<int> prime;int prim[101010];void init(){    for(int i=2;i<1500;i++)    {        if(!prim[i])        {        prime.push_back(i);        for(int j=i*2;j<1500;j+=i){            prim[j]=1;        }        }    }}int pp(int xx){    int len=prime.size();    int ans=0;    for(int i=0;i<len&&i<=sqrt(xx);i++)    {        if(xx%prime[i]==0)        {            ans++;            while(xx%prime[i]==0)            {                xx/=prime[i];            }        }    }    if(xx>1)    {        ans++;    }    return ans;}int main(){    int x,y;    init();    while(cin>>x>>y)    {        int l=y/x;        int ans=0;        if(y%x==0)        {        int res=pp(l);         ans=0;        ans+=pow(2,res);    }        printf("%d\n",ans );    }}
0 0
原创粉丝点击