题目:模幂运算-要求算法返回幂运算a^b的计算结果与1337取模后的结果
其中b是一个非常大的数,所以b使用数组形式表示。即无法直接a^b%1337计算
此类问题的关键需要分治,拆分成更小规模的计算
1)对于a^b,如果b=1234,则a^1234 = a^4 *(a^123)^10
即a^b可以拆分后递归运算
2)对于取模运算,(a*b)%k= (a%k)*(b%k)%k
证明a=Ak +B,b=Ck+D
则a*b = ACk^2+ADk+BCk+BD
则a*b%k= BD%k=(a%k)*(b%k)%k
所以上述问题,a^1234方如果数值比较大,则可以a%k * a^1233 ,递归算出所有的
所以算法为
/** * a的【1,2,3】幂次方取余数1337,计算 其中【1,2,3】可以无限大 */ public class Power { /** * a的【1,2,3】幂次方取余数1337,计算 其中【1,2,3】可以无限大 * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { BlockingDeque<Integer> blockingDeque = new LinkedBlockingDeque<>(); blockingDeque.add(1); blockingDeque.add(2); blockingDeque.add(3); int a = 2; //1) a^[1,2,3] = a^3 * (a^[1,2])^10 //2) a*b%c = (a%c)*(b%c)%c int i = superPower(a, blockingDeque); System.out.println(i); } public static int superPower(int a, BlockingDeque<Integer> blockingDeque) throws InterruptedException { if(blockingDeque.isEmpty()){ return 1; } int last = blockingDeque.takeLast(); int base = 1337; int part1 = myPower(a,last,base); int part2 = myPower(superPower(a,blockingDeque),10,base); return (part1*part2)%base; } public static int myPower(int a,int k,int base){ a = a % base; int res = 1; for(int i=0;i<k;i++){ res = res * a; res = res % base; } return res; }
3)幂运算仍可以进一步优化
即a^b = a * a^b-1 b为奇数, = (a^(b/2))^2
则可以进一步优化为
import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; /** * a的【1,2,3】幂次方取余数1337,计算 其中【1,2,3】可以无限大 */ public class Power2 { /** * a的【1,2,3】幂次方取余数1337,计算 其中【1,2,3】可以无限大 * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { BlockingDeque<Integer> blockingDeque = new LinkedBlockingDeque<>(); blockingDeque.add(1); blockingDeque.add(2); blockingDeque.add(3); int a = 2; //1) a^[1,2,3] = a^3 * (a^[1,2])^10 //2) a*b%c = (a%c)*(b%c)%c // 3) a^k = // // 3.1) (a^[k/2])^2 // // 3.2) a * a^[k-1] int i = superPower2(a, blockingDeque); System.out.println(i); Double res = Math.pow(a,123)%1337; String s = String.valueOf(res); System.out.println(s.substring(0,s.length()-2)); } public static int superPower2(int a, BlockingDeque<Integer> blockingDeque) throws InterruptedException { if(blockingDeque.isEmpty()){ return 1; } int last = blockingDeque.takeLast(); int base = 1337; int part1 = myPower2(a,last,base); int part2 = myPower2(superPower2(a,blockingDeque),10,base); return (part1*part2)%base; } public static int myPower2(int a,int k,int base){ if(k==0){ return 1; } a = a % base; if(1 == k%2){ return (a*myPower2(a,k-1,base))%base; }else{ int res = myPower2(a, k / 2, base); return (res*res)%base; } } }
标签:取模,运算,b%,int,1337,base,public,blockingDeque From: https://www.cnblogs.com/yangh2016/p/18371396