Vision_MATH_快速幂||矩阵快速幂
来源:互联网 发布:php面试技巧 编辑:程序博客网 时间:2024/05/21 19:42
///定义:
/*
快速幂就是快速算底数的n次幂。其时间复杂度为 O(logN), 与朴素的O(N)相比效率有了极大的提高。
也就是求A^B%mod的值,其中A可以是数字也可以是矩阵(矩阵快速幂)
*/
/*
快速幂就是快速算底数的n次幂。其时间复杂度为 O(logN), 与朴素的O(N)相比效率有了极大的提高。
也就是求A^B%mod的值,其中A可以是数字也可以是矩阵(矩阵快速幂)
*/
///代码:
/***name:快速幂**function:求解a^b%mod的值(mod*mod不会爆long long的情况)**输入参数:a,b,mod**输出参数:a^b%mod*/typedef long long LL;LL Q_pow(LL a,LL b,LL mod){ LL ans = 1; while(b){ if(b&1)ans=ans*a%mod; a=a*a%mod; b>>=1; } return ans;}
/***name:快速幂**function:求解a^b%mod的值(mod*mod会爆long long的情况)**输入参数:a,b,mod**输出参数:a^b%mod*/typedef long long LL;LL modular_multi(LL a, LL b, LL c) {/// a * b % c LL res, temp; res = 0, temp = a % c; while (b) { if (b & 1) { res += temp; if (res >= c) { res -= c; } } temp <<= 1; if (temp >= c) { temp -= c; } b >>= 1; } return res;}LL modular_exp(LL a, LL b, LL mod) { ///a ^ b % mod 改成mod_pow就不行,中间发生了溢出,还是这个模板靠谱 LL res, temp; res = 1 % mod, temp = a % mod; while (b) { if (b & 1) { res = modular_multi(res, temp, mod); } temp = modular_multi(temp, temp, mod); b >>= 1; } return res;}
/***name:矩阵快速幂**function:求解A^b%mod的值(A为矩阵)*/struct Matrix{ int a[2][2];//矩阵大小根据需求修改 Matrix() { memset(a,0,sizeof(a)); } void init() { for(int i=0;i<2;i++) for(int j=0;j<2;j++) a[i][j]=(i==j); } Matrix operator + (const Matrix &B)const { Matrix C; for(int i=0;i<2;i++) for(int j=0;j<2;j++) C.a[i][j]=(a[i][j]+B.a[i][j])%MOD; return C; } Matrix operator * (const Matrix &B)const { Matrix C; for(int i=0;i<2;i++) for(int k=0;k<2;k++) for(int j=0;j<2;j++) C.a[i][j]=(C.a[i][j]+1LL*a[i][k]*B.a[k][j])%MOD; return C; } Matrix operator ^ (const int &t)const { Matrix A=(*this),res; res.init(); ///矩阵的单位矩阵初始化 int p=t; while(p) { if(p&1)res=res*A; A=A*A; p>>=1; } return res; }};int main(){ Matrix A,ans; ans = A^b; return;}
///扩展:NULL
阅读全文
0 0
- Vision_MATH_快速幂||矩阵快速幂
- 快速矩阵快速幂
- 快速幂||矩阵快速幂
- 快速幂&矩阵快速幂
- 快速幂,矩阵快速幂
- 快速幂 矩阵快速幂
- 快速幂&矩阵快速幂
- 【快速幂】【矩阵快速幂】
- 快速幂和快速矩阵
- 快速乘/快速幂/矩阵快速幂
- 快速乘 快速幂 矩阵快速幂
- 快速幂,快速幂取模,矩阵快速幂
- 转移矩阵+矩阵快速幂
- 矩阵乘法 矩阵快速幂
- 构造矩阵+矩阵快速幂
- poj3070--矩阵 快速幂
- POJ3233矩阵快速幂
- poj3070Fibonacci 矩阵快速幂
- 初识Spring Boot框架(二)之DIY一个Spring Boot的自动配置
- Spark Shuffle原理、Shuffle操作问题解决和参数调优
- ConfigReader(五十二)—— ReadSkillFlyConfig
- Python获取路径中的文件名
- 记录
- Vision_MATH_快速幂||矩阵快速幂
- LeetCode——139. Word Break
- Spring AOP
- Hibernate 使用Query、SQLQuery 的setCacheable()设置缓存问题
- acdream 1234-Two Cylinders(辛普森积分)
- Servlet生命周期与工作原理(转载)
- nyoj119-士兵杀敌(三)(线段树,最大最小值)
- html5手机拍照上传
- SSM综合项目实战(TTSC) -- day05 搭建门户,内容管理,大广告位