Detailed explanation of fast exponentiation algorithm

Note: x y in this article means x to the power of y

When you ask for the value of n raised to the mth modulo k, what algorithm should you use to do it?

1. O(m) Naive Algorithm

The simplest method is simple simulation, which will not be introduced here. The code is as follows:

#include<bits/stdc++.h>
#define LL long long
using namespace std;
LL n,m,k;
intmain()
{	
    scanf("%lld%lld%lld",&n,&m,&k);	
    LL res=1;	
    for(int i=1;i<=m;i++) (res*=n)%=k;	
    printf("%lld",res);	
    return 0;
}

Second, the fast power algorithm

However, the naive algorithm of O(m) is still too slow after all, so we need a more efficient algorithm - fast power.

For x to the y power, we can have a classification discussion:

When y is even, x y =x y/2 *x y/2;

When y is odd, x y =x y/2 *x y/2 *x ("/" means divisible)

So, we can easily come up with an O ( log 2 m ) algorithm, the so-called fast exponentiation algorithm:

①Create a variable res of type long long to store the answer

② Judge the parity of m, if it is odd, multiply res by n, and take the modulo to k

③n square, m is divisible by 2

④If m is not 0, return ②

The specific code is as follows:

#include<bits/stdc++.h>
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
#define LL long long
using namespace std;
LL n,m,k;LL Counting(LL x,LL y,LL MOD)//快速幂函数
{	
    LL res=1;//Store the result 	
    while(y>0) {if(y&1) (res*=x)%=MOD;(x*=x)%=MOD,y>>=1;}//y&1 is equivalent to y%2,y>> =1 is equivalent to y/=2, speed up with bit operation 	
    return res;
}
intmain()
{
    scanf("%lld%lld%lld",&n,&m,&k);
    printf("%lld",Counting(n,m,k));
    return 0;
}



Note: If you have learned the fast exponentiation algorithm through this article, please like and leave. Of course, you are also welcome to point out the shortcomings of this article in the discussion area. The author will correct this article in time
. Copyright statement: Please indicate the address for reprinting


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325756690&siteId=291194637