一个数的整数次幂,是我们在计算中经常用到的,但是怎么可以在 \mathcal{O}(\log (n))O(log(n)) 的时间内算出结果呢?
代码框中的代码是一种实现,请分析并填写缺失的代码,求 x^y \mod pxymodp 的结果。
import java.util.*;
//x^ymodp
public class Main {
public static int pw(int x, int y, int p) {
if (y == 0) {
return 1;
}//终止条件
int res = pw(x*x,y/2,p) ;
//应用递归实现循环 看了大半天没有看出递归的直接巧妙之处
//y & 1 相当于取余运算
if ((y & 1) != 0) {
res = res * x % p;
}
return res;
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int x = cin.nextInt();
int y = cin.nextInt();
int p = cin.nextInt();
System.out.println(pw(x, y, p));
}
}