Fast Power remainder and power Remainder

Source: Internet
Author: User

Fast Power remainder and power Remainder

Evaluate a ^ B mod c

Algorithm 1.

First, design the algorithm directly:

int  ans=1, i;for(i=1;i<=b;i++)    ans*=a;ans%=c;

The time complexity of this algorithm is reflected in the for loop, which is O (B ).

This algorithm has obvious problems. If a and B are too large, it will easily overflow.

Let's take a look at the first Improvement Solution: before talking about this solution, we should first have a formula like this:

A ^ B mod c = (a mod c) ^ B

Theorem:

(A * B) mod c = [(a mod c) * (B mod c)] mod c;

Proof: Set a mod c = d, B mod c = e;

Then: a = t * c + d; B = k * c + e;

(A * B) mod c = (t * c + d) (t * c + e)

= (Tk c ^ 2 + (te + dk) * c + d * e) mod c

= De mod c

That is, the remainder of the product is equal to the remainder of the product.

(A ^ B) mod c can be obtained through iteration of the above formula (a mod c) ^ B.

After the above formula is proved, we can let a get the remainder of c first, which can greatly reduce the size of a, so we do not have to think about the improvement:

Algorithm 2:

Int ans = 1, I; a = a % c; // Add this sentence for (I = 1; I <= B; I ++) ans = ans *; ans = ans % c;

Since a factor is multiplied by the remainder and then the remainder remains the same, the newly calculated ans can also perform the remainder operation, so we can get a better version.

Algorithm 3:

Int ans = 1, I; a = a % c; for (int I = 1; I <= B; I ++) ans = (ans * a) % c; // here, the remainder ans = ans % c is obtained again;

 

This algorithm has not been improved in terms of time complexity. It is still O (B), but it is much better. However, it is likely to time out when c is too large, we have introduced the following fast power algorithms.

The rapid idempotence relies on the following formula:


 

Then we can get the following algorithm:

Algorithm 4:

Int ans = 1, I; a = a % c; if (B % 2 = 1) ans = (ans * a) mod c; // if it is an odd number, if you need to take more steps, you can calculate them to ans in advance. K = (a * a) % c; // we take a ^ 2 instead of a for (I = 1; I <= B/2; I ++) ans = (ans * k) % c; ans = ans % c;


We can see that we have changed the time complexity to O (B/2 ).

Of course, this is a permanent cure.

But we can see that when we make k = (a * a) mod c, the status has changed and the final result we require is k ^ (B/2) mod c

Instead of the original a ^ B mod c, we found that this process can be iterated. Of course, there will be one more a mod c for the odd number case, so to complete the iteration, when B is an odd number, we use ans = (ans * a) % c;

To make up for this extra item, then the remaining part can be iterated.

After iteration of the formula above, when B = 0, all the factors are multiplied and the algorithm ends.

Therefore, it can be completed in O (log B) time.

So we have the final algorithm: quick power algorithm.

Algorithm 5: Fast Power Algorithm

int ans = 1;a = a % c; while(b>0) {       if(b % 2 == 1)          ans = (ans * a) % c;     b = b/2;     a = (a * a) % c;  }  


Structure the code above, that is, write it as a function:

long long  PowerMod (int a, int b, int c) {      int  ans = 1;     a = a % c;     while(b>0) {          if(b % 2 = = 1)             ans = (ans * a) % c;         b = b/2;       //   b>>=1;        a = (a * a) % c;     }     return ans; }  


The time complexity of this algorithm is O (logb), which can be passed in almost all programming (competition) processes. It is one of the most common algorithms currently.

 

The following content is for reference only:

Extension: There is a derivation of the fast power algorithm. You can also think about it from another perspective.

A ^ B % c to solve this problem, we can also consider the Binary Conversion:

Convert the hexadecimal value of B to 2.

Hexadecimal expression:

 

Note that an here is either 0 or 1. If it is 0, this item is 1, which corresponds to the case where B is an even number in the above algorithm;

1 corresponds to the case where B is an odd number.


Pascal fast power: Remainder

{Enter the value of B, p, k, and evaluate the value of B ^ p mod k. Where B, p, k * k is a long integer.
Example input: 2 10 1000, output: 24}
Var B, p, k, t, ans: longint;
Begin
Readln (B, p, k );
Ans: = 1; t: = B;
While p> 0 do
Begin
If odd (p) then ans: = ans * t mod k;
P: = p div 2;
T: = t * t mod k;
End;
Writeln (ans );
End.

The following is a program for getting the remainder of the nth entry of the Fibonacci series in the matrix's fast power solution, but it always runs an error.

According to the normal logic, only a [2] [2] = {1, 1, 1, 0} The n (a [0] [1]) of the Fibonacci series can be obtained from the Npower of the matrix. However, if you ignore this, you are requesting a [0] [1], a [1] [0], when you set the value of a [1] [1], your value of a [0] [0] has actually changed, as a result, the value of a [0] [1] You obtained is incorrect, which affects the values of a [1] [0] And a [1] [1.
Therefore, when traversing these four values, we cannot change any of them. We can only change the value after the change. Therefore, we can use several variables to first store the obtained new matrix values, as shown below:
# Include <stdio. h>
Int a [2] [2] = {1, 1, 0}, B [2] [2] = {1, 1, 0 }; // use two-dimensional arrays to represent the matrix used by the fast power algorithm
Int main ()
{
Int n, m, I, j, t, u;
Int a1, a2, a3, a4;
While (scanf ("% d", & n, & m )! = EOF)
{
If (m =-1 & n =-1) // end the entire algorithm when the input m. n value is-1.
Return 0;
/* The following is the calculation of the nth Fibonacci number */
If (n = 0)
A [0] [0] = 0;
Else if (n = 1 | n = 2)
A [0] [0] = 1;
Else
{
For (I = 3; I <= n; I ++)
{
A1 = a [0] [0] * B [0] [0] + a [0] [1] * B [1] [0];
A2 = a [0] [0] * B [0] [1] + a [0] [1] * B [1] [1];
A3 = a [1] [0] * B [0] [0] + a [1] [1] * B [1] [0];
A4 = a [1] [0] * B [0] [1] + a [1] [1] * B [1] [1];
A [0] [0] = a1;
A [0] [1] = a2;
A [1] [0] = a3;
A [1] [1] = a4;
}
}
T = a [0] [0];
A [0] [0] = 1; // resets the matrix.
A [0] [1] = 1;
A [1] [0] = 1;
A [1] [1] = 0;
If (m = 0)
A [0] [0] = 0;
Else if (m = 1 | m = 2)
A [0] [0] = 1;
Else
{
For (j = 3; j <= m; j ++)
{
A1 = a [0] [0] * B [0] [0] + a [0] [1] * B [1] [0];
A2 = a [0] [0] * B [0] [1] + a [0] [1] * B [1] [1];
A3 = a [1] [0] * B [0] [0] + a [1] [1] * B [1] [0];
A4 = a [1] [0] * B [0] [1] + a [1] [1] * B [1] [1];
A [0] [0] = a1;
A [0] [1] = a2;
A [1] [0] = a3;
A [1] [1] = a4;
}
}
U = a [0] [0];
A [0] [0] = 1; // resets the matrix.
A [0] [1] = 1;
A [1] [0] = 1;
A [1] [1] = 0;
T = t % u;
Printf ("% d \ n", t );
}
Return 0;
}

Another point is that the two items after the multiplication of your matrix are wrong. Let's make a comparison.

In this way, you can get the desired result.
... Remaining full text>

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.