首页 > 其他 > 详细

【NOIP2012】同余方程

时间:2019-10-07 11:45:21      阅读:64      评论:0      收藏:0      [点我收藏+]

原题:

求关于xx的同余方程ax≡1(mod b)的最小正整数解。

 

裸题

当年被这题劝退,现在老子终于学会exgcd了哈哈哈哈哈哈哈哈

ax≡1(mod b) => ax=1+by => ax-by=1 => ax+by=1

若要保证有解,必须满足gcd(a, b)|1即gcd(a, b)=1

那么exgcd搞完之后只需加减b就能得到最小非负整数解

注意这里不是在解出y<0的情况下让x=-x

因为这里符号变化的是b,也就是说如果要求输出y,那么y应该等于-y

而跟x没有什么关系

 

代码:

技术分享图片
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cmath>
 6 using namespace std;
 7 #define LL long long
 8 LL exgcd(LL a,LL b,LL &x,LL &y){
 9     if(!b){  x=1,y=0;  return a;}
10     LL d=exgcd(b,a%b,x,y);
11     LL _x=x,_y=y;
12     y=_x-(a/b)*_y,x=_y;
13     return d;
14 }
15 LL a,b;
16 int main(){
17     //freopen("ddd.in","r",stdin);
18     cin>>a>>b;
19     LL x,y,d;
20     d=exgcd(a,b,x,y);
21     //if(y<0)  x=-x;
22     x=(x%b+b)%b;
23     cout<<x<<endl;
24     return 0;
25 }
View Code

 

【NOIP2012】同余方程

原文:https://www.cnblogs.com/cdcq/p/11629714.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!