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
- N=0, also known as A^n=1, at this time the mold is 1%b
- N=1, when the two points have reached the end, you can directly use A%B to get answers
- 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)