有一个很有名的数学逻辑题叫做不死神兔问题。有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第二十个月的兔子对数为多少?
public class RabbitPairs {
// 递归方法计算斐波那契数列
public static int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
// 迭代方法计算斐波那契数列
public static int fibonacciIterative(int n) {
if (n == 1 || n == 2) {
return 1;
}
int a = 1, b = 1, c;
for (int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
// 主方法,用于测试
public static void main(String[] args) {
// 使用迭代方法计算第二十个月的兔子对数
int month = 20;
int rabbitPairs = fibonacciIterative(month);
System.out.println("第二十个月的兔子对数为:" + rabbitPairs + "对。");
}
}