扩展欧几里得,逆元初识(poj 1061+codeforce 7C line+hdu 1576 A/B)




poj 1061 青蛙的约会:

#include <iostream>
#include<cstdio>
#define LL long long
using namespace std;
LL gcd(LL a, LL b){
   return b?gcd(b,a%b):a;
}
void extend_Euclid(LL a,LL b,LL &x,LL &y){
if(b == 0) {
   x = 1;
   y = 0;
   return ;
}
extend_Euclid(b,a%b,x,y);
LL tmp = x;  
x = y;
y = tmp - (a / b) * y;
}
LL res(int a,int b){
    while(a<0){
        if(b<0)a-=b;
        else a+=b;
    }
    return a;
}
int main()
{
    LL x,y,m,n,L;
    LL a,b,c,xi,yi;
    while(~scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&L)){
        a=m-n; b=L; c=y-x;
        LL d=gcd(a,b);
        if(c%d!=0){
           cout<<"Impossible\n";
           continue;
        }
        a/=d; b/=d; c/=d;
        extend_Euclid(a,b,xi,yi);
        xi=(xi*c)%b; //通解x不会比L长,所以要提前mod(b).
        xi=res(xi,b);
        cout<<xi<<endl;
    }
    return 0;
}

codeforce 7C line:

题意:判断一个线性方程组Ax+By+C=0是否有整数解,如果有,则输出整数解,否则输出-1.

并非是需要x一定要>0,利用扩展欧几里得求得x0,y0后再乘以相关倍数(-C/d)即可  [ d=gcd(A,B) ].

#include <iostream>
#include<cstdio>
#include<cmath>
#define LL long long
#include<cmath>
using namespace std;
void extend_Euclid(LL a,LL b,LL &f,LL &x,LL &y){
if(b == 0) {
   x = 1;
   y = 0;
   f=a;
   return ;
}
extend_Euclid(b,a%b,f,x,y);
LL tmp = x;
x = y;
y = tmp - (a / b) * y;
}
int main()
{
    LL A,B,C,f,x,y;
    while(cin>>A>>B>>C){
        extend_Euclid(A,B,f,x,y);
        if(C%f!=0){
           cout<<"-1\n";
           continue;
        }
        cout<<x*(-C/f)<<" "<<y*(-C/f)<<endl;
    }
    return 0;
}


hdu 1576 A/B

题意:要求(A/B)%9973,但由于A很大,我们只给出n(n=A%9973)(我们给定的A必能被B整除,且gcd(B,9973) = 1)。数据的第一行是一个T,表示有T组数据。
每组数据有两个数n(0 <= n < 9973)和B(1 <= B <= 10^9)。对应每组数据输出(A/B)%9973。

已知n=A%9973,设x=A/B,那么n=A-A/9973*9973=Bx-A/9973*9973,求出x大问题就解决了,最后为了防止负数产生,x=(x%9973+9973)%9973.

#include <iostream>
#include<cstdio>
#include<cmath>
#define LL long long
#include<cmath>
using namespace std;
void extend_Euclid(LL a,LL b,LL &f,LL &x,LL &y){
if(b == 0) {
   x = 1;
   y = 0;
   f=a;
   return ;
}
extend_Euclid(b,a%b,f,x,y);
LL tmp = x;
x = y;
y = tmp - (a / b) * y;
}
int main()
{
    //freopen("cin.txt","r",stdin);
    LL n,B,N;
    while(cin>>N){
         while(N--){
              LL a,b,c,f,x,y;
              scanf("%lld%lld",&n,&B);
              c=n;  b=9973;  a=B;
              extend_Euclid(a,b,f,x,y);
              x=x*(c/f);
              cout<<(x%9973+9973)%9973<<endl;
         }
    }
    return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值