Topic Link: Hdu 2035 people to see people love a^b
Very early time to do a problem, today think to turn him out, write an article to do not know the fast power of the students to do a popular science (please allow me to blow a bit). The power operation can be calculated efficiently by the fast power. If we use loops to calculate, then the time complexity is O (n), using the fast power of the word only with O (log n). Do not underestimate such a little, if a problem requires a number of power operations, it may be because of this little change and time-out.
Quick Power Introduction:
We always say fast power, so where is he going? If we solve 2^k. It can be represented as
X^n = ((x ²) ² .....)
As long as the K-squared operation is possible, we can think of, first, n is represented as 2 power-side second and
n = 2^k1 + 2^k2 + 2^k3 ....
's Got
X^n = x^ (2^K1) x^ (2^K2) x^ (2^K3) ....
So fast power is so fast. You can simulate it manually with a pen and paper.
Example: x^22 = x^16 x^4 x^2
Quick-Power templates:
typedef long Long LL; Note that this is not necessarily a long long sometimes int also line
ll Mod_pow (ll X, ll N, ll MoD) {
ll res = 1;
while (n > 0) {
if (N & 1) res = res * x% MoD; N&1 actually here and n%2 expression is a meaning
x = x * x% mod;
n >>= 1; N >>= 1 This and n/=2 expression is a meaning
}
return res;
Don't look at the arithmetic of children's shoes, well back to see, a lot of places are using this thing
Recursive version of:
typedef long long LL;
ll Mod_pow (ll X, ll N, ll MoD) {
if (n = = 0) return 1;
ll res = MOD_POW (x * x% mod, N/2, mod);
if (n & 1) res = res * x% MoD;
return res;
}
The following code is attached:
#include <stdio.h>
int mod_pow (int x, int n,int mod) { //fast power
int res = 1;
while (n > 0) {
if (N & 1) res = res * x% MoD;
x = x * x% mod;
n >>= 1;
}
return res;
}
int main () {
int m,n;
while (scanf ("%d%d", &m,&n), n| | m)
printf ("%d\n", Mod_pow (m,n,1000));
return 0;
}
Fast power Extension: Matrix fast power
(If there is an error, please correct it, reproduced in the source)