快速计算类似斐波那契数列数列的数列的第N项,矩阵快速幂
2024-08-24 12:46:24
这个题有循环节,可以不用这么做,这个可以当一个模板
#include <iostream>
#include <cstdio> using namespace std;
typedef long long ll;
struct matrix{
int r,c;ll m[5][5];
};
matrix A,B,C,D;
int n;
void init(){
A.m[1][1]=3;A.m[1][2]=1;
B.m[1][1]=1;B.m[1][2]=1;
B.m[2][1]=-1;B.m[2][2]=0;
A.r=1;A.c=2;
B.r=2;B.c=2;
}
void multyply(matrix &A,matrix B){
int i,j,k;
if(A.c!=B.r) printf("err\n");
for(i=1;i<=A.r;++i){
for(j=1;j<=B.c;++j){
C.m[i][j]=0;
for(k=1;k<=A.c;++k){
C.m[i][j]+=A.m[i][k]*B.m[k][j];
}
}
}
A.c=B.c;
for(i=1;i<=A.r;++i){
for(j=1;j<=B.c;++j){
A.m[i][j]=C.m[i][j];
}
}
}
void fast_pow(ll b){
if(b==0) return;
D.m[1][1]=1;D.m[1][2]=0;
D.m[2][1]=0;D.m[2][2]=1;
D.r=2;D.c=2;
while(b){
if(b&1){
multyply(D,B);
}
multyply(B,B);
b>>=1;
}
multyply(A,D);
}
int main(){
int T;scanf("%d",&T);
while(T--){
scanf("%d",&n);
init();
if(n==1){
printf("%d\n",1);
}
else if(n==2){
printf("%d\n",4);
}
else{
if(n-1==2){
printf("%d\n",6);
}
else{
fast_pow(n-3);
printf("%I64d\n",3+A.m[1][1]);
}
}
}
return 0;
}
最新文章
- iOS App 不支持http协议 App Transport Security has blocked a cleartext HTTP (http://)
- 搜索引擎关键词劫持之php篇(源码与分析)
- 【BZOJ 4456】【UOJ #184】【ZJOI 2016】旅行者
- Vue.js进阶
- JS深入了解闭包
- ArrayList调用remove方法需要注意的地方
- winston 日志管理4
- 函数查询(Function Query)
- tools安装
- Ios学习
- 素数判定 AC 杭电
- ecshop 微信支付插件
- cocos2d-x 3.0 使用最新物理引擎的一个源代码实例
- CSS3秘笈:第六章
- `define、parameter、localparam三者的区别
- UnityShader-菲涅尔反射(Fresnel Reflection)
- Python中布尔值是False的所有值
- Windows 运行命令大全,装逼必备哦!
- VS2015右键集成TortoiseGit
- project 2013 设置工期为1个工作日,但开始时间与结束时间不是同一天