标签:菲波那切数列
/**
* @author 韦轩
* @time 2015/07/26
* @brief 递归求菲波那切数列的第N项
* @param n,无符号的整数,要求的第N项
* @return 返回第N项
*
*/
long long getNthNumberWithRecursion(unsigned int n)
{
int result[2] = { 0, 1 };
if (n < 2)
return result[n];
return getNthNumberWithRecursion(n - 1) + getNthNumberWithRecursion(n - 2);
}
/**
* @author 韦轩
* @time 2015/07/26
* @brief 迭代求菲波那切数列的第N项
* @param n,无符号的整数,要求的第N项
* @return 返回第N项
*
*/
long long getNthNumberWithNoRecursion(unsigned int n)
{
int result[2] = { 0, 1 };
if (n < 2)
return result[n];
long long total = 0, first = 0, second = 1;
for (unsigned int i = 2; i <= n; i++)
{
total = first + second;
first = second;
second = total;
}
return total;
}
-时间复杂度:
-空间复杂度:
我们把Fibonacci数列中相邻的两项:F(n)和F(n - 1)写成一个2x1的矩阵,然后对其进行变形
/**
* @author 韦轩
* @time 2015/07/26
* @brief 二维矩阵
*
*/
struct Matrix2By2
{
long long m_00;
long long m_01;
long long m_10;
long long m_11;
Matrix2By2
(
long long m00 = 0,
long long m01 = 0,
long long m10 = 0,
long long m11 = 0
)
:m_00(m00), m_01(m01), m_10(m10), m_11(m11){}
};
/**
* @author 韦轩
* @time 2015/07/26
* @brief 矩阵相乘
* @param 两个矩阵
* @return 矩阵相乘的结果矩阵
*
*/
Matrix2By2 MatrixMultiply(const Matrix2By2& matrix1,const Matrix2By2& matrix2)
{
return Matrix2By2(
matrix1.m_00 * matrix2.m_00 + matrix1.m_01 * matrix2.m_10,
matrix1.m_00 * matrix2.m_01 + matrix1.m_01 * matrix2.m_11,
matrix1.m_10 * matrix2.m_00 + matrix1.m_11 * matrix2.m_10,
matrix1.m_10 * matrix2.m_01 + matrix1.m_11 * matrix2.m_11);
}
/**
* @author 韦轩
* @time 2015/07/26
* @brief 矩阵的N次方
* @param
* @return
*/
Matrix2By2 MatrixPower(unsigned int n)
{
assert(n > 0);
Matrix2By2 matrix;
if (n == 1)
{
matrix = Matrix2By2(1, 1, 1, 0);
}
else if (n % 2 == 0)
{
matrix = MatrixPower(n / 2);
matrix = MatrixMultiply(matrix, matrix);
}
else if (n % 2 == 1)
{
matrix = MatrixPower((n - 1) / 2);
matrix = MatrixMultiply(matrix, matrix);
matrix = MatrixMultiply(matrix, Matrix2By2(1, 1, 1, 0));
}
return matrix;
}
/**
* @author 韦轩
* @time 2015/07/26
* @brief 使用矩阵计算获得菲波那切数列的第N项
* @param
* @return
*
*/
long long getNthNumberWithMatrix(unsigned int n)
{
int result[2] = { 0, 1 };
if (n < 2)
return result[n];
Matrix2By2 PowerNMinus2 = MatrixPower(n - 1);
return PowerNMinus2.m_00;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:菲波那切数列
原文地址:http://blog.csdn.net/weiyongxuan/article/details/47073857