Thursday, May 31, 2007

Q1: multiplying rabbits

Question: A newly born rabbit is capable of reproducing at one month old (when it matures). Suppose the rabbit never dies, and it continues reproducing one new rabbit every month. So, when the rabbit is born, it has one member in its own family. After a month, it matures, and by the second month it adds a new born member to its family. In the third month, the rabbit produces another offspring; its first child also matures and will be ready to have an offspring in the next month. How many pairs of rabbits can be produced in a year from a single pair?

Answer: Let us write down the sequence of the rabbit number: 1, 1, 2, 3, 5, 8, 13 ... . It is a Fibonacci numbers.

The following code is the implementation in Java.

public class Fibonacci {
public static int getFibonacci(int n){
if(n < 0) return 0;
if((n == 0) || (n == 1)) return 1;
return getFibonacci(n-1) + getFibonacci(n-2);
}

public static void main(String[] args) {
for(int n=-1; n < 13; n++)
System.out.println(n + ": \t" + Fibonacci.getFibonacci(n));
}
}
}

The result:
-1: 0
0: 1
1: 1
2: 2
3: 3
4: 5
5: 8
6: 13
7: 21
8: 34
9: 55
10: 89
11: 144
12: 233

No comments: