這樣才能使對矩陣快速冪有深入的理解!!!
(其余基礎的不懂就請看我另一篇簡書!!!)
代碼如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#define CLR(x) memset(x,0,sizeof(x));
using namespace std;
struct point
{
int a[2][2]; //= {1,1,1,0};
void cclear()
{
CLR(a);
}
point operator * ( const point &b) const { //重載 * 號運算符.
point tmp;
tmp.cclear();
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
for(int k=0;k<2;k++){
tmp.a[i][j] += (a[i][k] * b.a[k][j]);
}
}
}
return tmp;
}
};
point x,res; //res是單位矩陣,用來存結果,相當于數快速冪重中的 數字 1 .
void init()
{
x.cclear(); //清空
res.cclear();
x.a[0][0] = 1; //fibroacci數列矩陣形式,怎么推出來請在網上搜索.
x.a[0][1] = 1;
x.a[1][0] = 1;
x.a[1][1] = 0;
res.a[0][0] = 1; //初始化為單位矩陣.
res.a[0][1] = 0;
res.a[1][0] = 0;
res.a[1][1] = 1;
}
void qpow(int n)
{
while(n){
if(n&1) res = res * x; // 不能寫成res *= x ; 因為我們只是重載了,* 號運算符, 而沒有重載 *= 運算符!
x = x * x;
n >>= 1;
}
}
int main()
{
int n;
printf("你想知道fibonacci數列的第幾項?\n");
while(scanf("%d",&n)!=EOF){
init();
if(n < 3){
printf("1\n");
continue;
}
qpow(n-2); //至于怎么推這個幾次方,就是用等比數列來推!!! an = a(n-1) * q ;
printf("%d\n",res.a[0][0]*1+res.a[1][0]*1);
}
}