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
题目大意:
一只青蛙在 (x,y)点,即 x,y 的最小公倍数 lcm(x,y)=k,则他下一步可以跳到 (x+k,y)或 (x,y+k)。现在给出一个终点坐标 (ex,ey),问你这只青蛙可以从多少个不同的点跳到这个终点。
解题思路:
对于点(x,y),记他们的最大公约数 gcd(x,y)=g,那么有
l
c
m
(
x
,
y
)
=
x
∗
y
/
g
c
d
(
x
,
y
)
lcm(x,y)=x*y/gcd(x,y)
lcm(x,y)=x∗y/gcd(x,y)。
我们记
x
=
m
1
∗
g
,
y
=
m
2
∗
g
x=m1*g,y=m2*g
x=m1∗g,y=m2∗g,所以有
k
=
m
1
∗
m
2
∗
g
k=m1*m2*g
k=m1∗m2∗g,所以下一步的
x
x
=
m
1
∗
g
∗
(
1
+
m
2
)
,
y
y
=
m
2
∗
g
xx=m1*g*(1+m2),yy=m2*g
xx=m1∗g∗(1+m2),yy=m2∗g(另一种也是一个道理)。
因为
m
1
和
m
2
m1 和 m2
m1和m2 互质,
m
2
和
m
2
+
1
m2和m2+1
m2和m2+1 也互质,所以我们可以发现,无论怎么跳,x,y的最大公约数都不会变。
所以我们可以通过这一点来逆着推,由下一步来推上一步。我们容易知道小的那个坐标应该是没用移动的坐标,所以有:
x
x
=
x
+
(
x
∗
y
)
/
g
,
y
y
=
y
xx=x+(x*y)/g,yy=y
xx=x+(x∗y)/g,yy=y
=
>
=>
=>
m
1
=
x
x
/
(
y
y
+
g
)
,
x
=
m
1
∗
g
;
m1=xx/(yy+g),x=m1*g;
m1=xx/(yy+g),x=m1∗g;
m
2
=
y
y
/
g
,
y
=
m
2
∗
g
;
m2=yy/g,y=m2*g;
m2=yy/g,y=m2∗g;
当公约数发生变化的时候就说明不能再往回跳了。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int t,ans;
ll ex,ey;
ll gcd(ll a,ll b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
void dfs(ll x,ll y)
{
if(x==y)
return;
//if(gcd(x,y)==1) return;
if(x<y)
swap(x,y);
ll k=gcd(x,y);
if(x%(y+k)!=0||y%k!=0)
return;
ll m1=x/(y+k),m2=y/k;
x=m1*k;
y=m2*k;
ans++;
dfs(x,y);
}
int main()
{
scanf("%d",&t);
int ca=0;
while(t--)
{
scanf("%lld%lld",&ex,&ey);
ans=1;
dfs(ex,ey);
printf("Case #%d: %d\n",++ca,ans);
}
return 0;
}