Fast Power algorithm, power algorithm
2016.1.25 my first article
When a simple algorithm needs O (B) time complexity for computation operations such as AB, B is obviously not desirable when B is large, so we hope to find a fast algorithm for calculation, especially when the answer is required to be modulo.
For simple algorithms, we have
Ans = 1;
For (int I = 1; I <= B; I ++) (ans * = a) % = mod;
We can simply optimize it by adding a % = mod before the loop;
When B is an even number, we can do this.
Ans = 1;
For (int I = 1; I <= B/2; I ++) (ans * = a) % = mod;
(Ans * = ans) % = mod;
Special Judgment is required when B is an odd number.
Ans = 1;
For (int I = 1; I <= B/2; I ++) (ans * = a) % = mod;
(Ans * = ans) % = mod;
If (B & 1) (ans * = a) % = mod;
In this way, the time can be halved.
We can even do this.
Ans = 1;
For (int I = 1; I <= B/4; I ++)
{
(Ans * = a) % = mod;
}
(Ans * = ans) % = mod;
(Ans * = ans) % = mod;
If (B & 1) (ans * = a) % = mod;
If (B/2) & 1) (ans * = a * a) % = mod;
We will naturally think that if the time can be halved, halved, and halved, the time complexity can be reduced to O (log n ).
The implementation method is also very simple, that is, the above steps are iterated multiple times.
The Code is as follows:
Int ans = 1; a % = mod; while (B) {if (B & 1) (ans * = a) % = mod; B/= 2; // you can know that any number greater than 1 can reach B = 1 in this step multiple times, so you don't have to worry that ans won't get a value (a * = a) at last) % = mod ;}View Code