您的位置:首页 > 产品设计 > UI/UE

05_斐波那契数列(Fibonacci sequence)

2016-04-07 20:43 471 查看
package exercise;
/**
* 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,
* 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* 斐波那契数列(Fibonacci sequence),以兔子繁殖为例子而引入,故又称为“兔子数列”,
* 指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……
* 在数学上,斐波纳契数列以如下被以递归的方法定义:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*)
* @author lsq
*
*/
public class Fibonacci {

public static void main(String[] args) {
System.out.println("第1个月的兔子对数:1");
System.out.println("第2个月的兔子对数:1");
int f1 = 1, f2 = 1, f, M = 24;
for (int i = 3; i <= M; i++) {
//F(n-1):把本月之前的所有兔子对数保存在临时变量f中。
f = f2;

//F(n)=F(n-2)+F(n-1)
f2 = f1 + f2;

//F(n-2)
f1 = f;
System.out.println("第 "+i+"个月的兔子对数:"+f2);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: