Java large number modulo operation

Modular Exponentiation

In discrete mathematics, there are large-number modulo operations, such as the result of 3^644 mod 645, 3^644 mod 645 =36 is the correct result

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*/
	}
}

mathematical principles




Guess you like

Origin blog.csdn.net/qq_28816195/article/details/66528901