一、整数m ^ n % k 的快速幂:
ll quickpow(ll m, ll n , ll k){ ll ans = 1; while(n){ if(n & 1)//如果n是奇数 ans = (ans * m) % k; n = n >> 1;//位运算“右移1类似除2” m = (m * m) % k; } return ans; }
二、矩阵 M ^ n % mod 的快速幂:
struct Matrix { ll m[MAXN][MAXN]; //二维数组存放矩阵 Matrix(ll num[MAXN][MAXN]) { for(int i = 0 ; i < MAXN ; i++) for(int j = 0 ; j < MAXN ; j++) m[i][j] = num[i][j]; } //对数组的初始化 Matrix() {} }; Matrix operator * (Matrix &m1, Matrix &m2) { int i, j, k; Matrix temp; for (i = 0; i < MAXN; i++) { for (j = 0; j < MAXN; j++) { temp.m[i][j] = 0; for(k = 0 ; k < MAXN ; k++) temp.m[i][j] += (m1.m[i][k] * m2.m[k][j]) % mod; temp.m[i][j] %= mod; //注意每一步都进行取模 } } return temp; } Matrix quickpow(Matrix &M , ll n, ll mod) { Matrix tempans(base); //初始化为单位矩阵 while(n) { if(n & 1) tempans = tempans * M; //已经重载了* n = n >> 1; M = M * M; } //快速幂(类似整数) return tempans; }