## Power Fast Fast modulo exponentiation

1. Fast power

Fast power base number refers to a fast computing power of b, by using a bit operation to reduce the number of cycles to achieve rapid results obtained.

Bitwise operators: and binary arithmetic rules: 1 & 1 = 1, 0 & 1 = 0.

Code

``````int Pow(int a,int b){
int ans = 1;
int base = a;
while(b)
{
if(b & 1)
{
ans *= base;
}
base *= base;
b >>= 1;
}
return ans;
}
``````

Note:
IF statement refers to the b & 1 b is converted into a binary, see the last bit is 1, 0 hit, tired ride, 1 hit, will multiply the value multiplied tired to answer.
while loop b >> = 1, a shift operation, a movement to the right of b, meet the next if statement, the last original is obtained in the former (also equivalent to the original value in addition to b 2).

2. Fast-taking power
for power to the modulo, the focus is in the process of seeking power in modulo, if we directly use modular arithmetic is actually very slow. So we might as well add some content when power demand fast, so get results.

It should be a theorem: (a ^ b) mod c = (a mod c) ^ b mod c.

Core code:

``````int pow_mod(int a,int b,int c)
{
int ans = 1;
int base = a%c;
while(b)
{
if(b & 1) ans = (ans*base)%c;
base = (base*base)%c;
b >>= 1;
}
return ans;
}
``````

Theorem inside, is to have a base number of the modulo operation. Here we are at the time of assignment to the base on a modulo. Then for each modulo back, we actually use the distribution rate, so as to achieve power modulo.

Released four original articles · won praise 0 · Views 94

### Guess you like

Origin blog.csdn.net/m0_45861545/article/details/104032215
Recommended
Ranking
Daily