龟速乘&O(1)快速乘&快速幂&矩阵快速幂板子

龟速乘:

//快速乘O(logn)防止爆 long long 时使用。
inline ll mult_mod(ll a, ll b, ll m)
{
    ll res = 0;
    while(b){
        if(b&1) res = (res+a)%m;
        a = (a+a)%m;
        b >>= 1;
    }
    return res;
} 

快速乘O(1):

//快速乘O(1)卡时间可以用但是会爆 long long
inline ll mult_mod(ll a, ll b, ll c)
{
	return (a*b-(ll)((long double)a/c*b)*c+c)%c;
}

快速幂:

typedef long long ll
ll binaryPow(ll a, ll b, ll m){
	ll ans = 1;
	while(b > 0){
		if(b & 1){
			ans = ans * a % m;
		}
		a = a * a % m;
		b >>= 1; 
	} 
	return ans;
}

矩阵快速幂:

typedef long long ll;
const int maxn = 5;
const int maxa = 4;
#define MOD 1000000007
struct Maxtrix {
	ll m[maxn][maxn];
} ans, res;
ll n;
Maxtrix Mul(Maxtrix a, Maxtrix b)
{
	Maxtrix tem;
	for (int i = 1; i <= maxa; ++i) {
		for (int j = 1; j <= maxa; ++j) {
			tem.m[i][j] = 0;
		}
	}
	for (int i = 1; i <= maxa; ++i) {
		for (int j = 1; j <= maxa; ++j) {
			for (int k = 1; k <= maxa; ++k) {
				tem.m[i][j] = (tem.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
			}
		}
	}
	return tem;
}
Maxtrix q_power(ll N, Maxtrix ans, Maxtrix res)
{
	// ans = [f(n) f(n - 1)] res = [1 1]
	//                             		[1 0]
	while (N) {
		if (N & 1)
			ans = Mul(ans, res);
		res = Mul(res, res);
		N >>= 1;
	}
	return res;
}

你可能感兴趣的:(算法,数论)