The binary power of variable-cure method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.