模幂运算
public static int modPowerShow(int a, int k, int n){
System.out.println("*************************************************************************");
System.out.println("****NOTICE:["\" area should be replaced by blank so there is nothing]****");
System.out.println("****NOTICE:["(3=))" area should be replaced by three line equal]*********");
System.out.println("*************************************************************************");
System.out.println("i ki x y");
int now, x = 1, y = a, power;
for(int i = 0;;i++){
now = k % 2;
System.out.print(i + " " + now + " ");
power = (x * y) % n;
if(now == 1) {
System.out.print(x + "x" + y + "(3=)" + power + " ");
x = power;
}
else System.out.print(x + " ");
y = (y * y) % n;
System.out.println(a + "^(2^" + (i+1) + ")" + "(3=)" + y);
k /= 2;
if(k == 1)break;
}
power = (x * y) % n;
System.out.println("\ \ " + x + "x" + y + "(3=)" + power);
return power;
}
模逆运算
public static int modInverseShow(int d, int n){
System.out.println("*************************************************************************");
System.out.println("****NOTICE:["\" area should be replaced by blank so there is nothing]****");
System.out.println("*************************************************************************");
int up = n;
int down = d;
int inverseUp = 0;
int inverse = 1;
int times, temp;
System.out.println("\ u v q");
System.out.println(up + " 1 0 \");
System.out.print(down + " 0 1 ");
for(;;) {
times = up / down;
System.out.println(times);
temp = up - down * times;
up = down;
down = temp;
temp = inverseUp - inverse * times;
inverseUp = inverse;
inverse = temp;
System.out.print(down + " \ " + inverse + " ");
if(down == 1)return (inverse > 0) ? inverse : (inverse + n);
if(down <= 0)return -1;
}
}
注意:如果返回值为-1,可能出现意外情况(两数不互素等原因),请自行验算