问题描述
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,⋯1,2,⋯ from the bottom, so are the columns. At first the frog is sitting at grid (sx,sy)(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)(x,y), first of all, he will find the minimum zz that can be divided by both xx and yy, and jump exactly zz steps to the up, or to the right. So the next possible grid will be (x+z,y)(x+z,y), or (x,y+z)(x,y+z).
After a finite number of steps (perhaps zero), he finally finishes at grid (ex,ey)(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)(ex,ey)!
Sample Input
3
6 10
6 8
2 8
Sample Output
Case #1: 1
Case #2: 2
Case #3: 3
问题大意:
有一个起点(x0,y0),z是x0,y0的最小公倍数。青蛙下一步能走的路线是(x0+z,y0)或者(x0,y0+z)一直循环…直到走到终点(ex,ey)。
现在给你终点(ex,ey),问你起点有几种可能。
解题思路:
首先给你的终点可能本身就是起点(一步没走),然后分析x0和y0。
设gcd(x0,y0)=t,如果把x0和y0看成x0=qt,y0=pt,那么z=qpt。
假设我们走(x0,y0+z),那么现在变成了(x1,y1)=(qt,pt+qpt)=(qt,pt(1+q))。
可以发现他们之间的关系y1/y0=1+q,因为x1=qt,所以也可以写成y1/y0=1+x1/t。
如果我们先把x0和y0的t都约去,即把x0和y0看成x0=q,y0=p。
那么现在(x1,y1)=(q,p+qp)=(q,p(1+q))。那么他们之间的关系就是y1/y0=1+q=1+x1,也就是y1/(1+x1)=y0。
如果y/(1+x)能整除表示能够走下去,否则就退出。
同时我们知道如果是从前一步得到的(x,y),那么x,y中大的那个数就是加了z的那个数字。
代码实现(附注释)
#include<iostream>
#include<algorithm>
using namespace std;
int gcd(int x, int y)
{
if (x % y)
return gcd(y, x % y);
return y;
}//最大公约数
int f(int x, int y) {
int sum = 0;
int flag = 1;
while (flag)
{
if (x > y) swap(x, y);//假设上一步走的是y,那么y的值要大于x的值。
if (y % (1 + x)) //y/(1+x)能整除表示能够走下去,否则就退出。
{
flag = 0;
}
else //能够整除,起点数加一。
{
sum++;
y /= x + 1;
}
}
return sum;
}
int main() {
int n;
cin >> n;
int x, y;
for (int i = 1; i <= n; i++) {
cin >> x >> y;
int t =gcd(x, y);
x /= t;
y /= t;//先把x和y的t都约去
cout << "Case #" << i << ": " << f(x, y) + 1 << endl;//终点本身就是起点,一步没走,也视为一种情况。
}
return 0;
}