P1226 [Template] Fast exponentiation|| remainder operation (Luogu)

Original title portal

Insert picture description here
Idea: There are two approaches to this question: recursion and iteration. What I use here is the iterative method. First, define a long integer variable and assign a value. Next, determine whether the binary end of the exponent is 1, if 1 is an odd number, accumulate a, then square the base b, and then divide the exponent p Shift the binary 1 bit to the right, and repeat this process until p<=0 ends

Code reference

#include<iostream>
using namespace std;
typedef long long ll;
int main()
{
    
    
	ll b,p,k,ans;
	cin>>b>>p>>k;
	ans=1;
	cout<<b<<"^"<<p<<" mod "<<k<<"=";
	while(p > 0){
    
    
		if(p & 1)//b的二进制末尾为1,即奇数
			ans = ans * b % k;
		b = b * b % k;
		p >>= 1;//将b的二进制向右移1位数
	}
	cout<<ans%k;
	return 0;
}

Guess you like

Origin blog.csdn.net/Bertil/article/details/106794925