hdu5584LCM Walk+gcd

来源:互联网 发布:吃鸡为什么不优化 编辑:程序博客网 时间:2024/06/06 05:09

Problem Description
A frog has just learned some number theory, and can’t wait to show his ability to his girlfriend.

Now the frog is sitting on a grid map of infinite rows and columns. Rows are numbered 1,2,⋯ from the bottom, so are the columns. At first the frog is sitting at grid (sx,sy), and begins his journey.

To show his girlfriend his talents in math, he uses a special way of jump. If currently the frog is at the grid (x,y), first of all, he will find the minimum z that can be divided by both x and y, and jump exactly z steps to the up, or to the right. So the next possible grid will be (x+z,y), or (x,y+z).

After a finite number of steps (perhaps zero), he finally finishes at grid (ex,ey). However, he is too tired and he forgets the position of his starting grid!

It will be too stupid to check each grid one by one, so please tell the frog the number of possible starting grids that can reach (ex,ey)!

Input
First line contains an integer T, which indicates the number of test cases.

Every test case contains two integers ex and ey, which is the destination grid.

⋅ 1≤T≤1000.
⋅ 1≤ex,ey≤109.

Output
For every test case, you should output “Case #x: y”, where x indicates the case number and counts from 1 and y is the number of possible starting grids.

Sample Input

3
6 10
6 8
2 8

Sample Output

Case #1: 1
Case #2: 2
Case #3: 3

Source
2015ACM/ICPC亚洲区上海站-重现赛(感谢华东理工)

我们可以假设目前的位置x,y.设gcd(x,y)=k,x=m1k,y=m2k,LCM(x,y)=xygcd(x,y)=m1m2k
那么新的位置可能就有两个(x+LCM,y),x,y+LCM
对于x< y这种,肯定是变化y,自然对于x>y这种,肯定是变化x..所以只用讨论x< y这种时(x>y也行,随意啦)。。

对于x,y+LCM这种,假设有x<y+LCM
我们不妨考虑下新的位置的gcd。由于原来的x,y的gcd=k,那么m1,m2必然是互质的,新的x=m1x,y=m2k+m1m2k=m2k(1+m1),显然m1m2m1+1GCDxnow,ynow=k,之前的位置与新到的位置有相同的GCD。so..

ynow=yold+LCM(xold,yold)=yold+xoldyoldgcd(xoldyold)
yold=ynow1+xoldgcd
所以当有y%(1+x)==0时能找到另外一个起始点、

#include<bits/stdc++.h>using namespace std;#define LL long longint main(){    int t;    cin>>t;    for(int cas=1;cas<=t;cas++){        LL x,y;        cin>>x>>y;        int cnt=1;        if(x>y) swap(x,y);        LL d=__gcd(x,y);        while(y%(x+d)==0){            y=y/(1+x/d);            if(x>y) swap(x,y);            cnt++;            d=__gcd(x,y);        }        cout<<"Case #"<<cas<<": "<<cnt<<endl;    }    return 0;}
0 0
原创粉丝点击