Fast idempotent modulo _ C ++ and idempotent modulo _ C
I. Question Background
Base Number a, exponent B, modulo value mo
Ask ans = AB % mo
Ii. Simple Algorithm (skip if known)
Ans = 1, cyclically from I to B, and each time the ans = ans * a % mo
Time complexity O (B)
1 void power(int a,int b,int mo) 2 { 3 int i; 4 ans=1; 5 for (i=1;i<=b;i++) 6 { 7 ans*=a; 8 ans%=mo; 9 }10 }
Iii. Quick power
First, we will discuss
When B is an even number: AB = a (B/2) * 2 = (a2) B/2
When B is odd: AB = a * AB-1 = a * (a2) (b-1)/2
For example, 28 = (22) 4 27 = 2 * (22) 3
So we can iterate on it like this.
210 = (22) 5 = (22) * [(22) 2] 2
① ③
If 10 is an even number, the base number is 2 square meters, and the index is half [① → ②]
If 5 is an odd number, the base number is first proposed as the coefficient (22). If 4 is an even number, the base number is 22 and then square, half of the index [② → ③]
Summarized as follows:
When the index is greater than 1, if it is an even number, the index is divided by 2, the base Square
If it is an odd number, a base number coefficient is first proposed (this coefficient can be directly multiplied into ans), so the index is reduced by 1, and then according to the even number method.
When the index is 1, the answer is obtained.
Finally, we only need to modulo each time we multiply the time. The time complexity is O (log2b)
1 void power(int a,int b,int mo) 2 { 3 ans=1; 4 a%=mo; 5 while (b>0) 6 { 7 if (b%2==1) ans=ans*a%mo; 8 b/=2; 9 a=a*a%mo;10 }11 }