remainder operator || fast exponentiation

Topic description

Enter the values ​​of b, p, and k, and find the value of b^p mod k. Where b, p, k*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

Ideas:

Obviously anyone can take remainders and multiply

The key is to be fast

We know that powers have a property

x^n=(x^2)^(n/2)

In this way, we can reduce the time complexity to log level by bisection

You might say, what about n%2==1? ?

And simple, define another variable as a scratchpad, multiply x

Now there is another theorem

x^n=x^(n-1)*x

So n can be reduced by one

Finally, multiply the scratchpad by x.

Code:

#include<iostream>
#include<cstdio>
using namespace std;
int  a,b,s;
int res=1;
int pw(int j,int k)
{
    if(k==0)
    {
        res=res%s;
        return res;
    }
    j=j%s;
    if(k%2==1)
    {
        res=res*j;
        res=res%s;
        k--;
        pw (j, k);
    }
    else
    {
        k=k/2;
        j = j* j;
        pw (j, k);
    }    
}
intmain ()
{
    cin>>a>>b>>s;
    long long x=1;
    x=pw(a,b);
    cout<<a<<"^"<<b<<" mod "<<s<<"="<<x;
}

 

Guess you like

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