【数论 && 公式转换】HDU

来源:互联网 发布:软件开发工资待遇 编辑:程序博客网 时间:2024/05/18 03:52

Problem Description

输入T代表有T组测试数据,每组测试数据输入x,y代表终点。问你有多少个不同的起始点能到达终点?假设一个点(x0, y0)那么它下一步可以走(x0 + lcm(x0, y0), y0) 或者 (x0, y0 + lcm(x0, y0));

思路

假设令当前点为(x1, y1),我们可以转换一下x1 = p*t, y1 = q*t其中(t 为 gcd(x1, y1))
那么下一个点为(p*t (1 + q), q*t) 或者 (p*t, q*t(1 + p))因为p和q互质,q和(1+q)互质, 所以q和(1+q)*p互质。得知最大公约数t是不变的
假设令(x, y) = (p*t (1 + q), q*t) 。那么pt = x / (1 + q), qt = y, q = y / t。因为t是不变的所以gcd(pt, qt) == gcd(x, y)

#include<bits/stdc++.h>using namespace std;int gcd(int x, int y){    if(!y) return x;    else return gcd(y, x%y);}int main(){    int T, x, y, cas = 1;    scanf("%d", &T);    while(T--)    {        scanf("%d %d", &x, &y);        int ans = 0;        int lastt = gcd(x, y);//最大公约数一直不变        while(1)        {            ans++;            if(x < y) swap(x, y);            int t = gcd(x, y);            if(t != lastt) {//如果t发生改变,退出循环                ans--;                break;            }            if(x%(1+y/t) == 0)//求p*t,yq*t            {                x = x / (1+y/t);            }            else break;        }        printf("Case #%d: %d\n", cas++, ans);    }}
原创粉丝点击