HDU5584 LCM Walk(数论)

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 zzthat 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)!

Input

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

Every test case contains two integers exex and eyey, which is the destination grid. 

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

Output

For every test case, you should output " Case #x: y", where xx indicates the case number and counts from 11 and yy 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

 

题意:

这只青蛙起始时在(ex,ey)点,下一步往前进lcm(x,y)距离,即下一步为(x+lcm(x,y),y)或(x,y+lcm(x,y)),给你终点坐标(ex,ey),问你起点有多少种可能情况。分析一下样例:(6,10)没有上一步只能是(6,10),(6,8)可以有(6,8),(6,2),(2,8)可以有(2,8),(2,4),(2,2)。

解题思路:

可以分析得出 每次前进一步不变的坐标一定是x,y中较小的那一个

设x,y的最大公约数为d=gcd(x,y),设x=nd,y=md(可以想此时的n,m互质,每次的最大公约数都是固定的d所以可以把d约去)

(上个演草图吧,不要嫌弃=.=)

 

HDU5584 LCM Walk(数论)_第1张图片

(为什么躺下了_(:з)∠)_)

 

即是可以推出(n,m)可以由(n/(m+1),m)或(n,m/(n+1))得来。

当两种情况都找不到结果时(得出的结果没有整数)说明已经找到所有结果。

AC代码:

#include

typedef long long ll;

ll gcd(ll x,ll y)
{
	if(x%y) return gcd(y,x%y);
	return y;
}

int main()
{
	int t,tt=1;
	ll x,y;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld%lld",&x,&y);
		ll d=gcd(x,y);
		x/=d;
		y/=d;
		int flag1,flag2;
		int step=1;
		while(1)
		{
			flag1=0,flag2=0;
			if(x>y)
			{
				if(x%(y+1)==0)
				{
					x=x/(y+1);
					flag1=1;
					step++;
				}
			}
			else if(x

 

你可能感兴趣的:(ACM,数论只会GCD)