快速幂合集

P1226 【模板】快速幂 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
ll a,b,p;
ll quickpow(ll a,ll b){
    ll ans=1,base=a;
    while(b>0){
        if(b&1) ans=ans*base%p;
        base=base*base%p;
        b>>=1;
    }
    return ans;
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>a>>b>>p;
    cout<<a<<"^"<<b<<" mod "<<p<<"="<<quickpow(a,b)%p<<endl;
    
    return 0;
}

补上很久之前写的快速幂矩阵乘法,那个时候还很花哨

P1962 斐波那契数列 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

/*坚持就是胜利---for BUAA*/
#include<bits/stdc++.h>
//#include<iostream>
//#include<algorithm>
//#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define endl "\n"
const int INF=0x3f3f3f3f;
const int mod=1e9+7;
ll n;
struct matrix{
    ll c[3][3];
    matrix(){
        memset(c,0,sizeof(c));
    }    
    matrix operator*(const matrix &b)const{
        matrix t;
        for(int i=1;i<=2;i++){
            for(int j=1;j<=2;j++){
                for(int k=1;k<=2;k++){
                    t.c[i][j]=(t.c[i][j]+c[i][k]*b.c[k][j])%mod;
                }
            }
        }
        return t;
    }
}f,a;
void quickpow(ll n){
    f.c[1][1]=f.c[1][2]=1;
    a.c[1][1]=a.c[1][2]=a.c[2][1]=1;
    while(n){
        if(n&1){
            f=f*a;
        }
        a=a*a;
        n>>=1;
    }
}
void solve(){
    if(n<=2) cout<<"1"<<endl;
    else{
        quickpow(n-2);
        cout<<f.c[1][1]%mod<<endl;
    }
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>n;
    solve();
    return 0;
}

 

posted @ 2024-02-11 12:43  ACCbulb  阅读(17)  评论(0)    收藏  举报