Fast power of power OR multiplication by exponentiation

Source: Internet
Author: User
Tags power of power

About the fast power this algorithm, already did not want to say, very early also will this algorithm, but originally always rely on the template foggy, recently re-study, found that overlooked an important problem, that is, if the number of modulus is greater than the int type, even if for __int64 when should do, so you have to use the multiplication of fast Power + Power quickly.

The fast power is generally to solve the problem of exponentiation, obviously the idea is two points, the following paste on the fast power template:

1 __int64 Mulpow (__int64 a,__int64 p,__int64 m)2 {3__int64 ans =1;4      while(P)5     {6         if(p&1)7Ans = ans * a%m;8P >>=1;9A = a * a%m;Ten     } One     returnans; A}
View Code

However, the above code has a problem, it is not suitable for m over int, the following is a solution to the case of M over int

1__int64 multi (__int64 a,__int64 b,__int64 N)//Multiplication Fast Power2 {3__int64 temp=0;4      while(b)5     {6         if(b&1)7         {8temp+=A;9             if(temp>=n) temp-=N;Ten         } Onea<<=1; A         if(a>=n) a-=N; -b>>=1; -     } the     returntemp; - } -  -__int64 Mulpow (__int64 a,__int64 m,__int64 N)//Power Fast + { -__int64 temp=1; +a%=N; A      while(m) at     { -         if(m&1) temp=multi (temp,a,n); -A=multi (a,a,n); -m>>=1; -     } -     returntemp; in}
View Code

But the disadvantage is that the speed is slow, logn*logn

Fast power of power OR multiplication by exponentiation

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.