Fast Power modulus (2015.7.29)

Source: Internet
Author: User
Tags modulus

The remainder has a%, i.e.

Ten%3

Can get 1

But when the numbers are large (for example, 2999999), the computer may not be able to calculate

However, based on the conclusion of number theory, we can simplify it.

According to a*b mod C = ((a mod c) * (b mod c)) mod C

Can draw an mod b = (a mod b) n mod b

So, there's an mod b = (a mod b) n mod b = (a mod b) n/22 mod b = (AN/2 mod b) 2 mod b = (AN/2 mod b) 2 mod b

If you use Exp_mod (a,n,b) to represent an MoD B then it is exp_mod (a,n,b) = Exp_mod (a,n/2,b) *exp_mod (a,n/2,b) MoD b

Then we can keep the two powers, thus reducing the operation

There are several special cases to consider

    1. N=0, also known as A^n=1, at this time the mold is 1%b
    2. N=1, when the two points have reached the end, you can directly use A%B to get answers
    3. n is odd, at this time N/2 will be abandoned to the fractional part, will be less than a mod B, you can fill a mod b

The pseudo code is as follows

Exp_mod (a,n,b) {//a^n mod b    if n=0        1  mod b    if n= 1         returns a mod b    temp=exp_mod (a,n/2, B)// down two points    temp=temp^ 2%B    If n is odd        temp=temp*a%b    returns temp}

The code is as follows

Long Long LL; ll Exp_mod (ll a,ll n,ll b) {    ll t;     if (n==0return1%b;     if (n==1return a%b;    T=exp_mod (a,n/2, b);    T=t*t%b;     if ((n&1) = =1) t=t*a%b    ; return t;}

Attach a question COGS-1130. Take the remainder operation

Fast Power modulus (2015.7.29)

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.