package 模重复平方法; import java.math.BigInteger; import java.util.Scanner; /* * 要求: * 1编程实现模重复平方计算法 */ public class Ah { public static void main(String[] args) { BigInteger b,m,n; Scanner sc=new Scanner(System.in); System.out.println("请输入b"); b=sc.nextBigInteger(); System.out.println("请输入n"); n=sc.nextBigInteger(); System.out.println("请输入m"); BigInteger a=new BigInteger("1"); m=sc.nextBigInteger(); String t1=n.toString(2); int[] N=new int[t1.length()]; for(int i=0;i<=t1.length()-1;i++) { N[i]=Integer.parseInt(t1.substring(t1.length()-i-1,t1.length()-i)); } for(int j=0;j<=t1.length()-1;j++) { if(j!=t1.length()-1) { if(N[j]==1) a=(a.multiply(b)).remainder(m); if(N[j]==0) a=a.remainder(m); b=(b.multiply(b)).remainder(m); } else { if(N[j]==1) a=(a.multiply(b)).remainder(m); if(N[j]==0) a=a.remainder(m); } } System.out.println(a);//测试 } }