快速幂:比如说2的8次方,需要2自乘7次。而快速幂只需要3次。
列;计算 2 的 9 次方
幂为奇数时要乘一个底数 result*2;//result为最终结果
底数变为2*2 = 4;
幂除二取整 9/2 = 4;
底数变为4*4 = 16;
幂除二取整 4/2 = 2;
底数变为16*16= 256;
幂除二取整 2/2 = 1;
最后result*256 = 512;即:2^9 = 2*(4)^4 = 2*(16)^2 = 2*(256)^1 = 512;
//用递归实现快速幂
//此方法只适合在整形范围内
#include<stdio.h>
int power(int n, int k, int result) {
if (k == 0) return result;//当幂为0时直接结束
if (k%2) result = result*n;//幂为奇数时乘一次底数,且把幂转化为偶数
if (k == 1) return result;//幂为一时结束
power(n*n, k/2, result);
}
long long power(int n, int times) {
long long result = 1;
while (times) {
if (times&1) result = result * n % p;//判断奇偶
n = n * n % p;
times >>= 1;
}
return result;
}
int main() {
int n, k;
int result = 1;
while (~scanf("%d%d", &n, &k)) {
printf("%d\n", power(n, k, result));
}
}