题目:
求解模线性方程(线性同余方程)
linear congruence theorem
用扩展欧几里德算法求解模线性方程的方法∶
同余方程ax=b (mod n)对于未知数x有解,当且仅当b是gcd(a,n)的倍数。且方程有解时,方程有gcd(a,n)个解。
求解方程ax=b (mod n)相当于求解方程ax+ ny= b,(x, y为整数)why?
思路:
扩展欧几里得算法
package 数学问题;
//扩张欧几里得算法
public class case04_裴蜀等式 {
static long x;
static long y;
public static long ext_gcd(long a,long b){
if(b==0){
x=1;
y=0;
return a;
}
long res=ext_gcd(b,a%b);
//xy已经被下一层递归更新了
long x1=x;//备份
x=y;
y=x1-a/b*y;
return res;
}
//线性方程
public static long linearEquation(long a,long b,long m) throws Exception{
long d=ext_gcd(a,b);
if(m%d!=0) throw new Exception("无解");
long n=m/d;
x*=n;
y*=n;
return d;
}
public static void main(String[] args) throws Exception {
case04_裴蜀等式 a=new case04_裴蜀等式();
try {
a.linearEquation(2, 3, 1);
System.out.println(a.x+" "+a.y);
}catch (Exception e){
System.out.println("无解");
}
}
}