Binary power algorithm from left to right
# include <stdio.h>intLeftrightbinaryexponentiation (intAintb[4]);intRightleftbinaryexponentiation (intAintb[4]);//calculates a binary representation of 2 of 13 square 1101 is 13voidMain () {intb[]={1,1,0,1 }; intc[]={1,0, on,1 }; intA=2; printf ("%d\n", Leftrightbinaryexponentiation (A, b)); printf ("%d\n", Rightleftbinaryexponentiation (A, b));} /** * * * such as a^13 = a^ (1*2^3 + 1*2^2 + 0*2^1 + 1*2^0) * * @param a base * * @param b Power Binary Horner expression (array order power high to the end)*///Binary power from left to rightintLeftrightbinaryexponentiation (intAintb[4]){ intProduct =A; inti; //B[0] must be 1 (either 1 or 0) because it is the highest bit factor and the highest bit factor is only 1 for(i =1; I <4; i++) {Product= Product *product; if(B[i] = =1) Product*=A; } returnproduct;} /** * * * such as a^13 = a^ (1*2^3 + 1*2^2 + 0*2^1 + 1*2^0) * * a base * * b Power binary Horner expression (array Shun Order power High to the end) * * @return*/ //right-to-left binary power intRightleftbinaryexponentiation (intAintb[4]) { inti; intProduct =1; intterm =A; for(i =3; I >=0; i--) { if(B[i] = =1) Product*=term ; term*=term ; } returnproduct; } Right-to-left algorithm: The initial value of term is a. At the end of the first cycle is the square of a, and the second loop ends with a four-time square. One analogy .... Whether each cycle is multiplied by a to see if array B is 1, and 1 is multiplied by a.
The binary power of variable-cure method