#include <iostream>
using namespace std;
int Fabonacci(int n)
{
if(n < 1)
return -1;
if(n == 1 || n == 2)
return 1;
return Fabonacci(n - 1) + Fabonacci(n - 2);
}
int Fabonacci_unrecur(int n)
{
if(n < 1) return -1;
if(n == 1 || n == 2) return 1;
int c, a = 1, b = 1;
for(int i = 3; i <= n; ++i)
{
c = a + b;
a = b;
b = c;
}
return c;
}
//插播一个 求幂的trick 普通求幂晓得是O(N),这个trick阔以到log(N),分析
int myPow(int m, int n)
{
int res = 1;
while(n)
{
if(n & 1)
res *= m;
m *= m;
n >>= 1;
}
return res;
}
//扩展至矩阵幂
//int** mul(int (*a)[2], int (*b)[2])
//{
// int res[2][2];
// res[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0];
// res[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1];
// res[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0];
// res[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1];
// return res; //试图return一个2维数组,做不到
//}
void mul(int c[2][2], int a[2][2], int b[2][2]){
int t[4];
t[0] = a[0][0]*b[0][0] + a[0][1]*b[1][0];
t[1] = a[0][0]*b[0][1] + a[0][1]*b[1][1];
t[2] = a[1][0]*b[0][0] + a[1][1]*b[1][0];
t[3] = a[1][0]*b[0][1] + a[1][1]*b[1][1];
c[0][0] = t[0];
c[0][1] = t[1];
c[1][0] = t[2];
c[1][1] = t[3];
}
void matPow(int res[2][2], int m[2][2], int n)
{
while(n)
{
if(n & 1)
mul(res, res, m);
mul(m, m, m);
n >>= 1;
}
}
int Fabonacci_matrix(int n)
{
if(n < 1) return -1;
if(n == 1 || n == 2)
return 1;
int f1 = 1, f2 = 1;
int a[2][2] = {
{1, 0},
{0, 1}
};
int para[2][2] = {
{1, 1},
{1, 0}
};
matPow(a, para, n - 2);
return a[0][0] + a[0][1];
}
int main(void)
{
cout << Fabonacci_unrecur(15) << endl;
cout << Fabonacci_matrix(15) << endl;
return 0;
}
Q8.1
最新推荐文章于 2022-06-17 15:25:22 发布