Fibonacci(斐波那契)序列的递归算法大家都已经很熟悉了:
//
Fibonacci序列第n项的值
// 递归算法
unsigned int Fib1(unsigned int n)
{
if (n == 1 || n == 2 )
return 1 ;
else
return Fib(n - 1 ) + Fib(n - 2 );
}
// 递归算法
unsigned int Fib1(unsigned int n)
{
if (n == 1 || n == 2 )
return 1 ;
else
return Fib(n - 1 ) + Fib(n - 2 );
}
而且递归算法的缺点是效率太低,下面是非递归算法:
//
Fibonacci序列第n项的值
// 非递归算法
unsigned int Fib2(unsigned int n)
{
unsigned int nP, nPp, nRet;
if ((n == 1 ) || (n == 2 ))
nRet = nP = nPp = 1 ;
for (unsigned int i = 3 ; i <= n; i ++ )
{
nRet = nP + nPp;
nPp = nP;
nP = nRet;
}
return nRet;
}
// 非递归算法
unsigned int Fib2(unsigned int n)
{
unsigned int nP, nPp, nRet;
if ((n == 1 ) || (n == 2 ))
nRet = nP = nPp = 1 ;
for (unsigned int i = 3 ; i <= n; i ++ )
{
nRet = nP + nPp;
nPp = nP;
nP = nRet;
}
return nRet;
}
Fibonacci(斐波那契)序列:
Fib(n) = Fib(n - 1) + Fib(n - 2), n>1, Fib(1) = Fib(2) = 1
即:序列的第一和第二项是1,从第三项开始,后一项是前两项的和。
序列的前8项是:
1, 1, 2, 3, 5, 8, 13, 21