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));
- if(n < 0) return 0;
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:
Post a Comment