java大数求模的运算

来源:互联网 发布:廖雪峰python教程微盘 编辑:程序博客网 时间:2024/05/21 07:59

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

数学原理




0 0
原创粉丝点击