最小非负解
求 a x ≡ b ( m o d    p ) ax\equiv b(mod\; p) ax≡b(modp)的最小非负解。
公式化为: a x + p y = b ax+py=b ax+py=b
此时用扩展欧几里得算法求解即可。
/*
* Author : Jk_Chen
* Date : 2019-08-21-10.26.44
*/
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define rep(i,a,b) for(int i=(int)(a);i<=(int)(b);i++)
#define per(i,a,b) for(int i=(int)(a);i>=(int)(b);i--)
#define mmm(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define pill pair<int, int>
#define fi first
#define se second
#define debug(x) cerr<<#x<<" = "<<x<<'\n';
const LL mod=1e9+7;
const int maxn=1e5+9;
LL rd(){ LL ans=0; char last=' ',ch=getchar();
while(!(ch>='0' && ch<='9'))last=ch,ch=getchar();
while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
if(last=='-')ans=-ans; return ans;
}
/*_________________________________________________________head*/
LL Ex_gcd(LL a,LL b,LL &x,LL &y){
if(!b){
y=0,x=1;
return a;
}
LL ans=Ex_gcd(b,a%b,y,x);
y-=a/b*x;
return ans;
}
LL MinNotNeg(LL a,LL b,LL c){
if(!a&&!b){
return -(c!=0);
}
LL x,y;
LL G=Ex_gcd(a,b,x,y);
if(c%G)return -1;
x*=c/G; y*=c/G;
b=abs(b/G);
return (x%b+b)%b;
}
int main(){
LL a,b,p;
cin>>a>>b>>p;
cout<<MinNotNeg(a,p,b)<<endl;
return 0;
}
解的情况
- 显然,当 g c d ( a , p ) ∣ ̸ b gcd(a,p)|\not b gcd(a,p)∤b时,方程无解。
- 否则,在 [ 0 , p − 1 ] [0,p-1] [0,p−1]范围内的解的个数为 g c d ( a , p ) gcd(a,p) gcd(a,p)。
证明: 因为两个解的步长(差值)为 p g c d ( a , p ) \dfrac{p}{gcd(a,p)} gcd(a,p)p,所以显然个数为 g c d ( a , p ) gcd(a,p) gcd(a,p)
可以自己手模一下, 4 x ≡ 2 ( m o d    6 ) → ( x = 2 , 5 ) , 4 x ≡ 0 ( m o d    6 ) → ( x = 0 , 3 ) 4x\equiv 2(mod\;6)\to(x=2,5),4x\equiv 0(mod\;6)\to(x=0,3) 4x≡2(mod6)→(x=2,5),4x≡0(mod6)→(x=0,3)
例题
要输出最小正数解,只需要考虑下0的情况就可以了。
/*
* Author : Jk_Chen
* Date : 2019-08-21-10.26.44
*/
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define rep(i,a,b) for(int i=(int)(a);i<=(int)(b);i++)
#define per(i,a,b) for(int i=(int)(a);i>=(int)(b);i--)
#define mmm(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define pill pair<int, int>
#define fi first
#define se second
#define debug(x) cerr<<#x<<" = "<<x<<'\n';
const LL mod=1e9+7;
const int maxn=1e5+9;
LL rd(){ LL ans=0; char last=' ',ch=getchar();
while(!(ch>='0' && ch<='9'))last=ch,ch=getchar();
while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
if(last=='-')ans=-ans; return ans;
}
/*_________________________________________________________head*/
LL Ex_gcd(LL a,LL b,LL &x,LL &y){
if(!b){
y=0,x=1;
return a;
}
LL ans=Ex_gcd(b,a%b,y,x);
y-=a/b*x;
return ans;
}
LL MinNotNeg(LL a,LL b,LL c){
if(!a&&!b){
return -(c!=0);
}
LL x,y;
LL G=Ex_gcd(a,b,x,y);
if(c%G)return -1;
x*=c/G; y*=c/G;
b=abs(b/G);
return (x%b+b-1)%b+1;
}
int main(){
LL a,p;
cin>>a>>p;
cout<<MinNotNeg(a,p,1)<<endl;
return 0;
}