GCD & LCM 一个神奇的式子

来源:互联网 发布:阿沁淘宝店叫什么 编辑:程序博客网 时间:2024/06/06 06:56

Description

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

 

 

这道题的精髓就在于:

       a*b=GCD*LCM

=>  (a/GCD) * (b/GCD) = LCM/GCD

       这样一来,就可以把a,b(也就是题目中的p,q)的范围大大的缩小;

       并且可以发现,a/GCD , b/GCD互质。

       根据这条性质,可以排除更多种的情况。

 

代码实现:

#include<iostream>using namespace std;int GCD(int a,int b){    return b==0?a:GCD(b,a%b);}int main(){    int n,m;    while(cin>>n>>m){       int sum=0;       if(m%n!=0){           cout<<"0"<<endl;           continue;           }       int m1=m/n;       for(int i=1;i<=m1;i++){                  if(m1%i==0){                        if(GCD(i,m1/i)==1){                            sum++;                            }                            }                            }     cout<<sum<<endl;                            }    return 0;}

 

 

原创粉丝点击