【模板】快速幂
普通的快速幂
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #define lll long long 3 lll ksm(int,int); 4 int x,n; 5 int main() 6 { 7 scanf("%d%d",&x,&n); 8 printf("%lld",ksm(x,n)); 9 return 0; 10 } 11 lll ksm(int x,int n) 12 { 13 lll ret = x; n--; 14 while(n) 15 { 16 if(n & 1) ret *= x; 17 x *= x; 18 n >>= 1; 19 } 20 return ret; 21 }
矩阵快速幂
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #define maxn 105 3 #define mo 1000000007 4 #define lll long long 5 int n,m; 6 struct mat 7 { 8 lll ori[maxn][maxn]; 9 mat operator * (const mat &y) const 10 { 11 mat ret; 12 int i,j,k; 13 for(i=1;i<=n;i++) 14 for(j=1;j<=n;j++) 15 { 16 ret.ori[i][j] = 0; 17 for(k=1;k<=n;k++) 18 ret.ori[i][j] = (ret.ori[i][j]+ori[i][k]*y.ori[k][j])%mo; 19 } 20 return ret; 21 } 22 }; 23 mat A,ans; 24 mat ksm (int k,mat a) 25 { 26 mat ret = a; k--; 27 while(k) 28 { 29 if(k&1) ret = ret * a; 30 a = a*a; 31 k >>= 1; 32 } 33 return ret; 34 } 35 int main() 36 { 37 scanf("%d%d",&n,&m); 38 int i,j; 39 for(i=1;i<=n;i++) 40 for(j=1;j<=n;j++) 41 scanf("%d",&A.ori[i][j]); 42 ans = ksm(m,A); 43 for(i=1;i<=n;i++) 44 { 45 for(j=1;j<=n;j++) printf("%lld ",ans.ori[i][j]); 46 printf("\n"); 47 } 48 return 0; 49 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!