Fast power modulo algorithm "template"

Source: Internet
Author: User

The fast power to take the mold is actually a^b%c, this is the famous RSA public key encryption method, when a, B are very big time, the direct is not advisable, therefore uses the fast power to take the mold.

First you have to understand his principle, in fact, the use of two points of thought, the B in accordance with the binary expansion

b = P (n) *2^n + p (n-1) *2^ (n-1) +...+ P (1) * * + P (0). where P (i) (0<=i<=n) is 0 or 1.

So at this time a^b = a^ (P (n) *2^n + p (n-1) *2^ (n-1) +...+ P (1) * + P (0)) = a^ (P (n) *2^n) * a^ (P (n-1) *2^ (n-1)) *...* a^ (P (1) * 2) * A^P (0);

For P (i) =0 the case is not processed, since a^ (P (i) * 2^ (i-1)) = A^0 = 1;

So what we need to consider is just the case of P (i) =1:

a^ (2^i) = a^ (2^ (i-1) * 2) = (a^ (P (i) * 2^ (i-1))) ^2

"Http://baike.baidu.com/view/1431260.htm" is described here in detail.


Here is a non-recursive approach:

Long Long modexp (long long A, long long b, int mod) {    long long Res=1;    while (b>0)    {        //a=a%mod; (sometimes the value of n is too large to store a long long, so take the remainder first)        if (b&1)//& bit operations: The last one to determine the binary is 0 or 1, & Operation rules are 1 before and after the time is 1;            res=res*a%mod;        b=b>>1;//is equivalent to dividing by 2;        a=a*a%mod;    }    return res;}




Fast power modulo algorithm "template"

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.