一个农场有头母牛,现在母牛才一岁,要到四岁才能生小牛,四岁之后,每年生一头小牛。假设每次生的都是母牛,并且也遵守4 年才生育并生母牛的原则,并且无死亡,请问n 年后共有多少头牛?
先口算发现其中规律:
年份 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
---|---|---|---|---|---|---|---|---|---|---|
数量 | 1 | 1 | 1 | 2 | 3 | 4 | 6 | 9 | 13 | 19 |
很容易发现f(n)=f(n-1)+f(n-3),典型的斐波那契数列类型的问题,可以直接套用。
方法一:使用递归
package qq;
public class qq {
public static void main(String[] args) {
for (int counter = 1; counter <= 20; counter++){
System.out.println("第"+counter+"年:"+"共"+f(counter)+"头牛");
}
}
//使用递归
public static long f(long number) {
if ((number == 1) || (number == 2)||(number == 3))
return 1;
else
return f(number - 1) + f(number - 3);
}
}
方法二:使用for循环
package qq;
public class qq {
public static void main(String[] args) {
for (int counter = 1; counter <= 10; counter++){
System.out.println("第"+counter+"年:"+"共"+f(counter)+"头牛");
}
}
//使用for循环
public static long f(int n) {
if (n == 1 || n == 2 || n == 3) {
return 1;
}
long a = 1l, b= 1l, c = 1l, d = 0l; //定义4个long类型整数
for (int i = 0; i < n - 3; i++) {
d = a + c; //第4个数的值等于第1个数和第3个数的和
a = b; //第2个数的值赋值给第1个数
b = c; //第3个数的值赋值给第2个数
c = d; //第4个数的值赋值给第3个数
}
return d;
}
}
运行结果
第1年:共1头牛
第2年:共1头牛
第3年:共1头牛
第4年:共2头牛
第5年:共3头牛
第6年:共4头牛
第7年:共6头牛
第8年:共9头牛
第9年:共13头牛
第10年:共19头牛