扩展欧几里得模板
如题= =自用模板

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class Exgcd{      
static long x=0;
static long y=0;
//ax+by=c;
//求x的最小正整数解
long minpositivex(long a,long b,long c){
long d = Math.abs(exgcd(a, b));
if (c % d!=0)
return -1;
long mod=b/d;
long x0 = ((x*(c/d))%mod+mod)%mod;
return x0;
}

//求y的最小正整数解
long minpositivey(long a,long b,long c){
long d = Math.abs(exgcd(a, b));
if (c % d!=0)
return -1;
long mod=a/d;
long y0 = ((y*(c/d))%mod+mod)%mod;
return y0;
}

long exgcd(long a,long b){
if (b == 0){
x = 1;
y = 0;
return a;
}
long d = exgcd(b, a % b);
long x1;
x1 = x;
x = y;
y = x1 - a / b * y;
return d;
}
static long gcd(long a,long b){
return a==0?b:gcd(b%a,a);
}
//return ax = b (mod n) 的最小解
long modular_linear_equation_solver(long a,long b,long n){
long d = exgcd(a, n);
if (b % d!=0)
return -1;
long x0 = x * (b / d) % n + n; // x0 * d 是 ax = b (mod n) 的一个解
return x0 % (n / d);
}
//中国剩余定理
/*long CRT(int a[],int mod[],int n) //mod是除数 a是余数 除数需互素
{
int M = 1;
long ans = 0;
for(int i=0; i<n; i++)
M *= mod[i];
for(int i=0; i<n; i++){
int Mi = M / mod[i];
exgcd(Mi, mod[i]);
ans = (ans + Mi * x * a[i]) % M;
}
if(ans < 0) ans += M;
return ans;
}*/
long CRT(int A[],int mod[],int n){ //mod是除数 a是余数 除数可不互素
long dm,a,b,d;
long c,c1,c2;
a=mod[0];
c1=A[0];
for(int i=1; i<n; i++){
b=mod[i];
c2=A[i];
d=exgcd(a,b);
c=c2-c1;
if(c%d!=0) return -1;//c一定是d的倍数,如果不是,则,肯定无解
dm=b/d;
x=((x*(c/d))%dm+dm)%dm;//保证x为最小正数//c/dm是余数,系数扩大余数被
c1=a*x+c1;
a=a*dm;
}
if(c1==0){ //余数为0,说明M[]是等比数列。且余数都为0
c1=1;
for(int i=0;i<n;i++)
c1=c1*mod[i]/gcd(c1,mod[i]);
}
return c1;
}

//乘法逆元
long mod_reverse(long a,long p){
long d=exgcd(a,p);
if(d==1) return (x%p+p)%p;
else return -1;
}
}