兔子繁衍问题C语言

兔子繁衍问题

一对兔子,从出生后第3个月起每个月都生一对兔子。小兔子长到第3个月后每个月又生一对兔子。假如兔子都不死,请问第1个月出生的一对兔子,至少需要繁衍到第几个月时兔子总数才可以达到N对?

输入格式

输入在一行中给出一个不超过10000的正整数N。

输出格式

在一行中输出兔子总数达到N最少需要的月数。

code

#include <stdio.h>
int main()
{
//a(n)=a(n-1)+a(n-2)
  int n,m=1,t=1,count=2;
  int sum =1;                //sum表示a(n)
  scanf("%d",&n);
  if(n==1){
    printf("1");
  }else{
      while(sum<n){
        count++;
        t=m;
        m=sum; //m在本轮循环中存放上一轮sum的值,留给下一轮赋值给t使用
        sum+=t;
      }
      printf("%d\n",count);
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/sharon_1995/article/details/89177821