[数论]HOJ 2185 Min Chain 扩展欧几里得算法

传送门:Min Chain

Min Chain

My Tags  (Edit)
  Source : 2009 China North East Local Contest
  Time limit : 2 sec   Memory limit : 64 M

Submitted : 387, Accepted : 103

Problem Description

Raven likes games of numbers. Today he meets two numbers and thinks whether he could get a result of 1 by doing at least one operation (addition or subtraction). However, he is tired of calculation; he also wants to know the minimum steps of operation that he could get 1.

Input Details

The first line of the input contains an integer T, which indicates the number of test cases.

In the following T rows, there are two positive integers a, b ( 0<=a, b<=10^9) in each row.

Output Details

For each case, output the least number of steps.

If you cannot get 1, just output -1.

Sample Input

3
3 2
16 9
6 8

Sample Output

1
10
-1

Hint

Sample 1: 3 - 2 = 1, One subtraction will be needed.
Sample 2: 16-9+16-9+16-9-9-9+16-9-9=1,It requires 10 additions and subtractions.
Sample 3: You cannot get 1.

解题报告:

分析:

扩展的欧几里德算法,ax+by=gcd(a,b),若gcd(a,b)!=1,输出-1,否则,用扩展的欧几里德算法求出

最小的x与y即可,注意到

当存在0时,若有1输出1,否则输出-1;

当存在1,若有2输出1,否则输出2(因为直接a-a+1即可)

当上面都不满足时,直接用扩展的欧几里德算法求出x,在解方程求出y,两绝对值相加减一即可

代码如下:

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
long long ext_gcd(long long a,long long b,long long &x,long long &y){
    if(b==0){
        x=1;y=0; return a;
    }
    long long d=ext_gcd(b,a%b,x,y);
    long long xt=x;
    x=y;
    y=xt-a/b*y;
    return d;
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        long long a,b,c=1;
        scanf("%lld%lld",&a,&b);
        if(b>a)
            swap(a,b);
        if(b==0){
            if(a==1)
                printf("1\n");
            else
                printf("-1\n");
        }
        else if(a==2&&b==1)
            printf("1\n");
        else if(b==1)
            printf("2\n");
        else{
            long long x,y;
            long long d=ext_gcd(a,b,x,y);
            if(d!=1)
                printf("-1\n");
            else{
                int e;
                e=x*c/b;
                x=c*x-e*b;
                y=(1-a*x)/b;
                long long ans=abs(x)+abs(y);
                printf("%lld\n",ans-1);
            }
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值