问题提出
一对兔子,从出生后第三个月起每个月都生一对兔子。小兔子长到第三个月后每个月又生一对兔子。假如兔子都不死,请问第一个月出生的一对兔子,至少需要繁衍到第几个月时兔子总数才能到达n对?
思路
由于兔子基数为一对,可以试用列举法观察规律(斐波那契数列)
月份 | 1 | 1 | 2 | 3 | 4 | 5 |
兔子对数 | 1 | 1 | 3 | 5 | 8 | 13 |
#include <stdio.h>
#include <math.h>
int main()
{
int n,month;
printf("请输入兔子的对数数量:\n");
scanf("%d",&n);
month=f(n);
printf("当兔子数量达到%d时,至少需要%d个月",n,month);
return 0;
}
int fun(int x)//返回兔子的数量
{
int n;
if(x==1||x==2)
n=1;
else
n=fun(x-1)+fun(x-2);
return n;
}
int f(int m)
{
int i=0,n=1;
while(n<m)
{
i++;
if(i==1||i==2)
n=1;
else
n=fun(i);
}
return i;
}