特殊同余方程-逆元方程

逆元方程

  • (A/B)%9973,求余,除法不满足交换性,可改为求B关于9973的逆元x,
  • 这样结果等价于Ax%9973等价于x*A%9973等价于xn%9973,
package _6数学问题;
import java.util.Scanner;
public class j逆元方程 {
//测试
	//87 123456789
	//结果6060
public static void main(String[] args) {
   Scanner in=new Scanner(System.in);
   int T=in.nextInt();
   for(int i=0;i<T;i++) {
	   int n=in.nextInt();//87
       int B=in.nextInt();//123456789
       try {
    	   //ax=b   99973余数
    		getlina(B,9973);//求B的逆元
             x = (x%9973 + 9973) % 9973;
            System.out.println(x * n % 9973);
	
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
   }
 
}
static int x;
static int y;
private static long getlina(int a, int b) throws Exception {
	// TODO Auto-generated method stub
	int d= getlin(a,b,1);
	 x=((x%b+b)%b);
     return d;	
}

private static int getlin(int a, int b, int d) throws Exception {
	// TODO Auto-generated method stub
	int f=getext(a,b);
	if(d%f!=0)throw new Exception();
	int beishu=d/f;
	x*=beishu;
	y*=beishu;
	return f;
}

private static int getext(int a, int b) {
	// TODO Auto-generated method stub
	if(b==0) {
		x=1;
		y=0;
		return a;
	}
	int d=getext(b,a%b);
	int x1=x;
	 x=y;
	 y=x1-a/b*y;
	return d;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_45952706/article/details/107799402
今日推荐