以 3 13 = 1594323 3^{13}=1594323 313=1594323为例
将指数 13 13 13写成二进制 1101 1101 1101
bit 1 1 0 1 base 3 8 3 4 3 2 3 1 \begin{matrix}\text{bit} & 1 & 1 & 0 & 1 \\ \text{base} & 3^8 & 3^4 & 3^2 & 3^1\end{matrix} bitbase138134032131
3 13 = 3 8 + 4 + 1 = 3 8 × 3 4 × 3 1 = 1594323 3^{13}=3^{8+4+1}=3^8\times3^4\times3^1=1594323 313=38+4+1=38×34×31=1594323
要点:指数二进制的当前位为1
时,对result
累乘base
long long pow( int x, int n )
{
long long result = 1, base = x;
while(n)
{
if( n & 1 )
result *= base;
base *= base;
n >>= 1;
}
return result;
}