Romantic( 线性方程)

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=88159#problem/I

题意:

      给你两个数a,b,是否有这样两个数x,y,使得ax+by=1方程成立,如果有输出x最小的一组数。x为非负整数。

      案例:

      input

      77 51 

      10 44

      34 79

      output

      2 -3

      sorry

      7 -3

思路分析:

       当a,b的公约数不为1时,是没有整数解的。

       详细思路可以进这个网页去了解。http://www.cnblogs.com/yuelingzhi/archive/2011/08/13/2137582.html

      需要注意的是,求出的x可能是负数,所以当x<0时,要让加上b,而y要减a。

源代码如下:

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 void gcd(int a,int b,int &d,long long &x,long long &y)
 5 {
 6     if(!b) {d=a;x=1;y=0;}
 7     else {gcd(b,a%b,d,y,x);y-=x*(a/b);}
 8 }
 9 int main()
10 {
11     int a,b,d;
12     long long x,y;        //必须为longlong型
13     while(scanf("%d%d",&a,&b)!=EOF)
14     {
15         gcd(a,b,d,x,y);
16         if(d!=1) printf("sorry\n");
17         else
18         {
19             while(x<0)
20             {
21                 x+=b;
22                 y-=a;
23             }
24             printf("%lld %lld\n",x,y);
25         }
26     }
27     return 0;
28 }

 

     

 

转载于:https://www.cnblogs.com/q-c-y/p/4749087.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值