P1226 [Template] Fast exponentiation || remainder operation

Topic description

Enter the values ​​of b, p, and k, and find the value of b^p mod k. Where b, p, k are long integers.

Input and output format

Input format:

 

Three integers b, p, k.

 

Output format:

 

output "b^p mod k=s"

s is the result of the operation

 

Input and output example

Input Example #1:  Copy

2 10 9

Output Sample #1:  Copy

2^10 mod 9=7

 


Ideas:

Quick power template questions, pay attention to use long long or there will be a few points stuck

 


Code:

#include<iostream>
#define ll long long
using namespace std;
ll b,p,k;

ll quickPower(ll a,ll b,ll m)
{
    ll ans=1,base=a;
    while(b > 0)
    {
        if(b & 1)//与 b mod 2 == 1等效,也就是奇数 
        {
            ans *= base;
            ans %= m;
        }

        base *= base;
        base %= m;
        b >>= 1; //与 b/=2 等效 
    } 
	return ans;
}

int main()
{
	ios::sync_with_stdio(false);
	cin>>b>>p>>k;
	cout<<b<<"^"<<p<<" mod "<<k<<"="<<quickPower(b,p,k)%k<<endl;
	return 0;
}

 

Guess you like

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