【模板】快速幂||取余运算。

拿一个样例说话吧:

2^1=2 2%9=2 
2^2=4 4%9=4 
2^3=8 8%9=8 
2^4=16 16%9=7 
2^5=32 32%9=5 
2^6=64 64%9=1
2^7=128 128%9=2

通过这个你能发现什么呢?

自然就是余数都是有规律的。

是不是让快速幂变得浅显易懂了。

其他规律就不在这里一一列出了。

直接双手奉上代码了。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cctype>
#define rg register
#define int long long
using namespace std;
inline int read(){
    rg char ch=getchar();
    rg int x=0,f=0;
    while(!isdigit(ch)) f|=(ch=='-'),ch=getchar();
    while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    return f?-x:x;
}
inline void write(int s){
    if(s<0) putchar('-'),s=-s;
    if(s>9) write(s/10);
    putchar(s%10+'0');
}
signed main(){
    int s,t,b,p,k;
    b=read();
    p=read();
    k=read();
    cout<<b<<"^"<<p<<" mod "<<k<<"=";
    s=b%k;
    t=1;
    for(rg int i=2;i<=p;++i){
        s=s*b%k;
        if(s==b%k) break;
        ++t;
    }
    p%=t;s=1;
    if(p==0) p=t;
    for(rg int i=1;i<=p;++i)
    s=s*b%k;
    write(s);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Sinyess/p/10088710.html