Modular Exponentiation
在离散数学里有大数求模的运算,例如求3^644 mod 645的结果,3^644 mod 645 =36是正确的结果
package ThisTestForProblems;
import javax.swing.JOptionPane;
public class ModularExponentiation {
public static void main(String[] args) {
/*The algorithm is to get the result b^n%m for example 3^644 % 645 =36 */
int b=Integer.parseInt(JOptionPane.showInputDialog("The algorithm to get the result of b^n % m. Please input the b "));
int n=Integer.parseInt(JOptionPane.showInputDialog("The algorithm to get the result of b^n % m. Please input the n"));
char[] array=Integer.toBinaryString(n).toCharArray();/*array is the binary string of the numberN*/
int m=Integer.parseInt(JOptionPane.showInputDialog("The algorithm to get the result of b^n % m. Please input the m "));
int k=array.length;
int x=1;
int power=b%m;
for(int i=0;i<k;i++){
if(array[k-1-i]=='1')
{
x=(x*power)%m;
}
power=(power*power)%m;
}
System.out.println(x);/*x is the result of b^n%m*/
}
}
数学原理