ax=1(%b) 求最小逆元

复制代码
 1    定理一:如果d = gcd(a, b),则必能找到正的或负的整数x和y,使 d = a*x+ b*y。
 2 
 3    定理二:若gcd(a, b) = 1,则方程ax ≡ c (mod b)在[0, b-1]上有唯一解。
 4 
 5    定理三:若gcd(a, b) = d,则方程ax ≡ c (mod b)在[0, b/d - 1]上有唯一解。
 6 
 7    对于ax+by=1;  即ax=1(mod b)      当且仅当gcd(a,b)!=1 的时候,无解!
 8 
 9  #include <iostream>
10  #include <cstdio>
11  #include <cstring>
12  #include <string>
13  #include <utility>
14  #include <stack>
15  #include <map>
16  #include <queue>
17  #include <vector>
18  #include <cmath>
19  #include <iostream>
20  #include <algorithm>
21  #define pi acos(-1.0)
22  #define e 2.718
23  #define lowbit(x) (x&(-x))
24  using  namespace std;
25  typedef unsigned long long  ull;
26  typedef long long ll;
27  int t,a,b;
28  int  egcd(int a,int b,int &x,int &y)
29  {
30      int d=a;
31      if(!b)
32      {
33          x=1,y=0;
34      }
35      else
36      {
37          d=egcd(b,a%b,y,x);
38          y-=x*(a/b);
39      }
40      return d;
41  }
42  int  solve(int a,int b)
43  {             int d,x,y;
44       d=egcd(a,b,x,y);
45      if(d!=1)
46      {
47          return -1;
48      }
49      else
50      {
51          while(x<=0)
52          {
53              x+=b/d;
54          }
55      }
56      return x;
57  }
58  int main()
59  {
60      scanf("%d",&t);
61      while(t--)
62      {
63          scanf("%d %d",&a,&b);
64          if(solve(a,b)==-1)
65          {
66              printf("Not Exist\n");
67          }
68          else
69          {
70              printf("%d\n",solve(a,b));
71          }
72      }
73      return 0;
74  }
复制代码

 

posted on   cltt  阅读(270)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示