Java Practice question: rabbit problem
This question is also called the Fibonacci sequence (Fabonacci), the first person to study the series is the Leonardo of Pisa (also known as the Fibonacci), which he used to describe the number of rabbits growing. The first month there are a couple of newborn rabbits. After the second month, they can have babies. Every month a pair of fertile rabbits will be born, and a new rabbit would never die.
Suppose that in the N month there are newborn and fertile rabbits in total a pairs, n+1 month has a total of b pairs. In n+2 months there must be a total of a+b pairs: Because during the n+2 months, all a pairs of rabbits that had existed in n months were already fertile and gave birth to a pair of offspring, while in the previous January (n+1 month) of B for Rabbits, the newly born rabbits were not fertile in the month. Refer to the following table:
The number of months passed |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 [] /td> |
|
All |
[ |
,
New born rabbit |
0 |
0 |
1 |
1 |
2 |
P>3 |
5 |
8 |
34 |
@ | @
|
+ |
Rabbit log |
1 |
1 |
2 |
3 |
5 |
8 |
|
, |
|
$ |
144 |
This can be defined by mathematical induction as:
F (n) = f (n-1) +f (n+1);(n>2,f (1) =1,f (2) =1);
What if we use the normal iterative method to implement it? Let's say we want to print the logarithm of the 12-month rabbit, the code reads:
public static void Main (String args[]) {
int r[] = new INT[12]; Number of rabbits per month
r[0] = 1; Number of rabbits in the first month
r[1] = 1; The Rabbit book for the second month for
(int a = 2; a < a++) {
R[a] = R[a-1] + r[a-2];
System.out.println (R[a]);
}
The code is simple, it is implemented in arrays, but if we use recursion, the code is simpler:
public static void Main (String args[]) {
System.out.println (FBI (12));//Print
}
static int Fbi (int i) {
if (I < 2) return i==0?0:1;
Return to the FBI (I-1) + FBI (I-2); Call your own function
}