注解:斐波纳契数
描述:
Fibonacci’soriginal question:
1. 给定一对兔子,一只公的,一只母的。
2. 兔子在一个月大时,可以进行交配,母兔在下一个月时,可以生出另一对兔子。
3.假设我们的兔子永不死亡。
4.假定每个母兔个月总是再生出一个兔子(一只是公的,一只是母的)
问题:一年以后,一共有多少对兔子?
解析:
1. In the beginning: (1 pair) 2. End of month 1: (1 pair) Rabbitsare ready to mate. 3. End of month 2: (2 pairs) A newpair of rabbits are born. 4. End of month 3: (3 pairs) A newpair and two old pairs. 5. End of month 4: (5 pairs) ... 6. End of month 5: (8 pairs) ... …….. 7.After 12 months, there will be233 pairs rabbits!
{0,1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …}
想法1:
Algotithm1 fib(n)
if n = 0 then return 0
if n = 1 then return 1
return (fib(n-1)+fib(n-2))
效率:T(n)= T(n−1) + T(n−2)+ 3≈1.6的n次方
T(200) >=
2的139次方
(291 seconds = 7.85 × 1019years )
想法2:用数组实现
Algorithm2:fib(n)
// Initially we create an array A[0:n]
A[0] ← 0, A[1] ← 1
For i= 2 to n do
A[i]= A[i− 1] + A[i− 2]
return (A[n])
相似问题:
/*<span style="font-size: 14px;">题目:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?</span>
*分析:
第一个月 1对
第二个月 1对
第三个月 2对 第2对成长1个月
第四个月 3对 第3对成长1个月 第2对成长2个月
第五个月 5对 第5对成长1个月 第4对成长1个月 第3对成长2个月
第六个月 8对 第8、7、6对成长1个月 第5、4对成长2个月
第七个月 13对
*难点: 找规律
1.为什么第三个月之后。每月的兔子的数量就是前两个月的兔子的数量的和?
*/
#include <stdio.h>
int main()
{
int m[23];
int i;
m[0]=m[1]=1;
for (i=0; i<24; i++)
{
if (i==0 || i==1)
{
printf("第%d个月为:1对\n",i+1);
}
else
{
m[i]=m[i-1]+m[i-2];
printf("第%d个月为:%d对\n",i+1,m[i]);
}
}
return 0;
}
/*版本二
#include <stdio.h>
int fun(int n)
{
for( n = 1;n<12;n++)
{
if (n==1 || n==2)
return 1;
else
return fun(n-1)+fun(n-2);
}
}
int main()
{
int mouth;
//printf("你需要查询第几个月兔子数");
scanf("%d",&mouth);
fun(mouth);
printf("第%d个月兔子数量为:%d对\n",mouth,fun(mouth));
return 0;
} */