标签:math 函数实现 type pen rac struct name quick turn
long long quick_pow(long long a,long long n)
{
long long ret;
while(n)
{
if(n&1)ret=ret*a;
a=a*a;
n>>=1;
}
return ret;
}
由于求矩阵的幂次的时候往往也会需要求数的快速幂,所以这里用模板函数实现。设矩阵在域(环)\(Z_M\)中运算,数在环(域)\(Z_N\)中运算。
注意数据类型都是
long long
,输入输出时须使用%lld
环中做除法:\(\frac{a}{b}\%M=\frac{a\%bM}{b}\)
struct matrix
{
long long a,b,c,d;
matrix(){}
matrix(long long m,long long n,long long p,long long q):a(m),b(n),c(p),d(q){}
matrix(long long x):a(x),b(0),c(0),d(x){}
};
matrix solve(matrix A,matrix B)
{
matrix ret;
ret.a=(A.a*B.a+A.b*B.c)%M;
ret.b=(A.a*B.b+A.b*B.d)%M;
ret.c=(A.c*B.a+A.d*B.c)%M;
ret.d=(A.c*B.b+A.d*B.d)%M;
return ret;
}
long long solve(long long x,long long y)
{
return x*y%N;
}
template<typename T>
T quick_pow(T a,long long n)
{
T ret(1);
while(n)
{
if(n&1)ret=solve(ret,a);
a=solve(a,a);
n>>=1;
}
return ret;
}
标签:math 函数实现 type pen rac struct name quick turn
原文地址:https://www.cnblogs.com/maoruimas/p/9551301.html