扩展欧几里得算法和线性同余方程
1.扩展欧几里得算法
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string.h> 5 #include <math.h> 6 #include <algorithm> 7 #include <stack> 8 #include <queue> 9 #include <vector> 10 #include <map> 11 #include <set> 12 #define ll long long 13 const int N=1e6+10; 14 using namespace std; 15 typedef pair<int,int>PII; 16 17 int exgcd(int a,int b,int &x1,int &y1){ 18 if(b==0){ 19 x1=1,y1=0; 20 return a; 21 } 22 int x2,y2; 23 int d=exgcd(b,a%b,x2,y2); 24 x1=y2,y1=x2-a/b*y2; 25 return d; 26 } 27 28 int main(){ 29 ios::sync_with_stdio(false); 30 int t; 31 cin>>t; 32 while(t--){ 33 int a,b,x1,y1; 34 cin>>a>>b; 35 exgcd(a,b,x1,y1); 36 37 printf("%d %d\n",x1,y1); 38 } 39 40 return 0; 41 }
2.线性同余方程
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <stack> 7 #include <queue> 8 #include <vector> 9 #include <map> 10 #include <set> 11 #include <unordered_set> 12 #include <unordered_map> 13 #define ll long long 14 #define fi first 15 #define se second 16 #define pb push_back 17 #define me memset 18 const int N = 1e6 + 10; 19 const int mod = 1e9 + 7; 20 using namespace std; 21 typedef pair<int,int> PII; 22 typedef pair<long,long> PLL; 23 24 int exgcd(int a,int b,int &x1,int &y1){ 25 int x2,y2; 26 if(b==0){ 27 x1=1,y1=0; 28 return a; 29 } 30 int d=exgcd(b,a%b,x2,y2); 31 x1=y2,y1=x2-a/b*y2; 32 return d; 33 } 34 35 36 int main() { 37 ios::sync_with_stdio(false); 38 int n; 39 cin>>n; 40 while(n--){ 41 int a,b,m; 42 int x1,y1; 43 cin>>a>>b>>m; 44 int d=exgcd(a,m,x1,y1); 45 if(b%d) printf("impossible\n"); 46 else printf("%lld\n",(ll)x1*(b/d)%m); 47 } 48 49 return 0; 50 }
𝓐𝓬𝓱𝓲𝓮𝓿𝓮𝓶𝓮𝓷𝓽 𝓹𝓻𝓸𝓿𝓲𝓭𝓮𝓼 𝓽𝓱𝓮 𝓸𝓷𝓵𝔂 𝓻𝓮𝓪𝓵
𝓹𝓵𝓮𝓪𝓼𝓾𝓻𝓮 𝓲𝓷 𝓵𝓲𝓯𝓮