Fibonacci sequence (rabbit reproduction problem)

Rabbit reproduction problem (15 points)

A pair of rabbits will give birth to a pair of rabbits every month from the 3rd month after birth. After the bunnies reach their third month, they will give birth to a pair of rabbits every month. If the rabbits don't die, may a pair of rabbits born in the first month need to reproduce at least in the first month before the total number of rabbits can reach N pairs?

Input format:
Input is given in one line as a positive integer N up to 10000.

Output format:
Output the number of months required for the total number of rabbits to reach N minimum in one line.

Input samples:
30
Output samples:
9

In fact, if you list the number of rabbits in the previous months, you will find that starting from the third month, the total number of rabbits in the next month is the sum of the total number of rabbits in the previous two months. In fact, this sequence is a golden algorithm problem. This sequence of numbers is called the Fibonacci sequence.
The Fibonacci sequence, also known as the golden section sequence, was introduced by the mathematician Leonardo Fibonacci with the example of rabbit breeding, so it is also called "rabbit sequence", referring to such a Sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, ... In mathematics, the Fibonacci sequence is defined recursively as follows: F(0)=1, F(1 )=1, F(n)=F(n-1)+F(n-2) (n>2, n∈N*). The sequence starts at term 3, and each term is equal to the sum of the previous two.

The non-recursive C++ code is implemented as follows:

#include<iostream>
using namespace std;

int main(void)
{
    int n, sum, cnt, v1, v2;
    sum = cnt = 1; //cnt表示过了几个月,sum为兔子总数 
    v1 = v2 = 0;
    cin >> n;
    if(n > 1) { //n至少是大于等于2的数,若为1,则直接输出cnt,即1 
        while(sum < n) { 
            v1 = v2; 
            v2 = sum;
            sum += v1;
            cnt ++;
        }
    }
    cout << cnt << endl;

    return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326658984&siteId=291194637