1. Fast power is the n power of fast calculation base. Its time complexity is O (log₂n), and the Simplicity of O (N) compared to the efficiency has been greatly improved.
Usage: Used to solve the B-side of a, and B is a very large number, and the complexity of O (n) times out. Then we need this algorithm, note that it can not only be the logarithm of the power, but also can be used for matrix fast power. --Baidu Encyclopedia
2. The so-called fast power, in fact, is the abbreviation of fast Power modulus, simply speaking, is to quickly find a power mode (residual). In the process of programming, it is often necessary to find the remainder of a number for a large number, and in order to get a faster and more computational range algorithm, a fast power modulus algorithm is produced.
We usually ask for a number of n power, is called the library function math.h inside the
Double pow (double x,double y) function.
However, since the return value of this method is double, there must be a problem with precision error.
And the data is a big easy time-out.
The purpose of the fast power is to achieve the power quickly.
Suppose you need to ask for a power of 11 times.
General Solution: A*a*a*a*a*a*a*a*a*a*a 11 steps
Fast power: a^ (2^0+2^1+2^3) is 2^1*a^2*a^8 3 steps
Because it is binary, it is natural to think of this powerful tool with bit operations:
& and >>
& operations are typically used for binary take operations, such as the result of a number & 1, which is the last digit of the binary. It can also be judged that the odd and even x&1==0 are even, x&1==1 is odd.
The >> operation is simple, the binary removes the last one
int poww (int a,int b) {
int ans=1,base=a;
while (b!=0) {
if (b&1!=0)
ans*=base;
Base*=base;
b>>=1;
}
return ans;
Assuming a power of 2 is required, the values of ANS and base are shown in the following table.
Title Description:
Algorithm to improve the fast power
Time limit: 1.0s memory limit: 256.0MB
Problem description
Given A, B, p, (a^b) mod p.
Input format
Enter a common row.
The first line has three numbers, N, M, P.
Output format
Outputs a total of one row, indicating the request.
Sample input
2 5 3
Sample output
2
Data size and conventions
A total of 10 sets of data
For 100% of the data, A, B is a long long range of non-negative integers, p is a nonnegative integer within int.
#include <stdio.h>
#define LL long long
int main ()
{
ll b,k;
int p;
scanf ("%i64d%d%i64d", &b,&p,&k);
ll T=1;
while (p)
{
if (P & 1)
t= (t*b)%k;
b= (b*b)%k;
p>>=1;
}
printf ("%i64d\n", t);
return 0;
}