1. 程式人生 > >HDU 5584 LCM Walk (lcm/gcd)

HDU 5584 LCM Walk (lcm/gcd)

aps review over divide inline lock check while ram

LCM Walk

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1834 Accepted Submission(s): 955


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.

? 1T1000.
? 1ex,ey109.

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那麽y要跳回上一步的話,
可以先分解為y=lcm(x,k)+k; 我們知道當x與k互質的時候,lcm(x,k)=x*k; 那麽讓x,y互質的話,x與k也會互質 我們可以想想,讓x,y互質是不會影響最終結果的 所以我們讓x,y除以它們的最大公因數,然後y=x*k+k; y=(x+1)k;即當y能夠整除x+1時,存在對應的k, 這時候的k和x,又成為了新一輪的x,y; 不斷的轉化下去,看又多少輪即可 代碼如下:
#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long ll;

int main()
{
    ll t;
    ll a,b;
    ll ans;
    ll gcd1;
    ll Case=0;
    scanf("%lld",&t);
    while(t--)
    {
        scanf("%lld%lld",&a,&b);
        Case++;
        if(a>b)swap(a,b);
        gcd1=__gcd(a,b);
        a=a/gcd1;
        b=b/gcd1;
        ans=1;
        while(1)
        {
          if(b%(a+1)!=0||a==0||b==0)break;
          b=b/(a+1);
          if(a>b)swap(a,b);
          ans++;
        }
        printf("Case #%lld: %lld\n",Case,ans);
    }
    return 0;
}

HDU 5584 LCM Walk (lcm/gcd)