求斐波那契数列的第n项(Fibonacci sequence)

法一(循环求解)

#include<iostream>
typedef long long LL;
using namespace std;

LL fibonacciSequence(int n)
{
 LL a = 1, b = 1, temp;
 if (n == 1 || n == 2)
  return 1;
 else
 {
  for (int i = 1; i < n; i++)
  {
   temp = b;
   b = a + b;
   a = temp;
  }
  return a;
 }
}

int main()
{
 int num;
 cin >> num;
 cout << fibonacciSequence(num);
 return 0;
}

法二(递归求解)

#include<iostream>
typedef long long LL;
using namespace std;

LL fibonacciSequence(int n)
{
 LL x;
 if (n == 1 || n == 2)
  x = 1;
 else
  x = fibonacciSequence(n - 1) + fibonacciSequence(n - 2);
 return x;
}

int main()
{
 int num;
 cin >> num;
 cout << fibonacciSequence(num);
 return 0;
}

法三(矩阵求解)

#include<iostream>
typedef long long LL;
using namespace std;

const int MAX = 10;
#define Bit(n) 1<<n
#define CLR(arr,val) memset(arr,val,sizeof(arr))

class Matrix
{
public:
 int Result() const{ return map[0][1] % 10000; }
 friend Matrix operator*(const Matrix&, const Matrix&);
 int Pow(int);
 LL map[MAX][MAX];
 int row, col;
 Matrix(int r, int c) :row(r), col(c)
 {}
 void Init()
 {
  CLR(map, 0);
  map[0][0] = map[0][1] = map[1][0] = 1;
 }
 void Unit() //初始化为单位矩阵 
 {
  CLR(map, 0);
  for (int i = 0; i < row; i++)
  {
   map[i][i] = 1;
  }
 }
};

Matrix operator*(const Matrix& M1, const Matrix& M2) //矩阵相乘模板
{
 Matrix M(M1.row, M2.col); //相乘之后矩阵的行和列会变化   
 for (int i = 0; i < M1.row; i++)
 {
  for (int j = 0; j < M2.col; j++)
  {
   M.map[i][j] = 0;
   for (int k = 0; k < M1.col; k++)
   {
    M.map[i][j] += M1.map[i][k] * M2.map[k][j];
   }
   M.map[i][j] %= 10000;
  }
 }
 return M;
}

Matrix M(2, 2);

int Matrix::Pow(int n) //矩阵快速幂
{
 Matrix temp(2, 2);
 temp.Init();
 for (int i = 0; Bit(i) <= n; i++) //利用二进制的思想求解 
 {
  if (Bit(i)&n) M = M*temp;
  temp = temp*temp;
 }
 return M.Result();
}

int main()
{
 int num;
 cin >> num;
 M.Unit();
 cout << M.Pow(num);
 return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43548474/article/details/89072679