(一)题目1:快速幂
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
分析
(数学前提)
(a+b) mod p = (a mod p + b mod p) mod p
(a*b) mod p = (a mod p * b mod p) mod p
举例
代码实现
public double myPow(double x, int n) {
double res = 1.0;
int k = n;
//注意:判断指数为负数情况
if(k<0){
k = -k;
}
while(k!=0){
if(k%2 == 1){
res = res *x;
}
x = x*x; // pow(3,1) -> pow(3,2) -> pow(3,4)
k /=2;
}
if(n<0){
res = 1/res;
}
return res;
}
(二)快速幂取模
题目
a^b mod p = ?
代码实现
public int fastmulti(int a,int b,int c){
int res = 1;
if(c == 1) return 0;
for(; b != 0; b /= 2){
if(b %2 == 0){
res = (res*a)%c;
}
a = (a*a)%c;
}
return res;
}