Fast to the power of the whole number of times, of course, can not directly die. As an example:
3 ^ 999 = 3 * 3 * 3 * ... * 3
Multiply directly by 998 times. But in fact can do this, first find out 2^k power:
3 ^ 2 = 3 * 3
3 ^ 4 = (3 ^ 2) * (3 ^ 2)
3 ^ 8 = (3 ^ 4) * (3 ^ 4)
3 ^ 16 = (3 ^ 8) * (3 ^ 8)
3 ^ 32 = (3 ^ 16) * (3 ^ 16)
3 ^ 64 = (3 ^ 32) * (3 ^ 32)
3 ^ 128 = (3 ^ 64) * (3 ^ 64)
3 ^ 256 = (3 ^ 128) * (3 ^ 128)
3 ^ 512 = (3 ^ 256) * (3 ^ 256)
Multiply again:
3 ^ 999 = 3 ^ (512 + 256 + 128 + 64 + 32 + 4 + 2 + 1)
= (3 ^ 512) * (3 ^ 256) * (3 ^ 128) * (3 ^ 64) * (3 ^ 32) * (3 ^ 4) * (3 ^ 2) * 3
So just do the multiplication 16 times. Even with some auxiliary storage and operations, it is much more efficient than direct multiplication (especially if the base is a large number of hundreds of thousands of digits).
We found that to convert 999 to 2 binary number: 1111100111, and all of them are to multiply the number. This suggests that we use the BITS algorithm (where mod is a modulo operation):
So you can write the following code:
Double Pow (doubleint n) { double1; while (n) { if1) //equivalent to if (n% 2! = 0 )*= x ; 1 ; *= x; } return result;}
Finally test the comparison with the POW function in the C standard library function:
#include <stdio.h>#include<math.h>#include<time.h>using namespacestd;#defineCOUNT 100000000DoublePow (DoubleXintN) { Doubleresult =1; while(n) {if(N &1) Result*=x; N>>=1; X*=x; } returnresult;}intMain () {intstart, end; Start=clock (); for(inti =0; i < COUNT; i++) Pow (2.0, -); End=clock (); printf ("Time =%d\n", (End-start)); Start=clock (); for(inti =0; i < COUNT; i++) Pow (2.0,100.0); End=clock (); printf ("Time =%d\n", (End-start)); return 0;}
The end result is about the same.
A fast exponentiation algorithm with non-recursive recursion