1. 程式人生 > >【模板】快速冪||取餘運算。

【模板】快速冪||取餘運算。

拿一個樣例說話吧:

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;
}