Skip to content

Instantly share code, notes, and snippets.

@yongboy
Created January 31, 2012 08:54
Show Gist options
  • Save yongboy/1709531 to your computer and use it in GitHub Desktop.
Save yongboy/1709531 to your computer and use it in GitHub Desktop.
单线程版本的斐波纳契数列求解参考实现
package com.learn.jsry166y.demo;
/**
* 单线程版本的斐波纳契数列求解参考实现<br/>
* 800年前,意大利的数学家斐波纳契出版了惊世之作《算盘书》。在《算盘书》里,他提出了著名的“兔子问题”:假定一对兔子每个月可以生一对兔子,
* 而这对新兔子在出生后第二个月就开始生另外一对兔子,这些兔子不会死去,那么一对兔子一年内能繁殖多少对兔子?
* 答案是一组非常特殊的数字:1,1,2,3,5,8,
* 13,21,34,55,89……不难发现,从第三个数起,每个数都是前两数之和,这个数列则称为“斐波纳契数列”,其中每个数字都是“斐波纳契数”。
*
* @author yongboy
* @time 2012-1-30
* @version 1.0
*/
public class SingleThreadFibonacci {
final public static int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
final int n;
SingleThreadFibonacci(int n) {
this.n = n;
}
private int compute(int small) {
return results[small];
}
public Integer compute() {
if (n <= 10) {
return compute(n);
}
SingleThreadFibonacci f1 = new SingleThreadFibonacci(n - 1);
SingleThreadFibonacci f2 = new SingleThreadFibonacci(n - 2);
return f1.compute() + f2.compute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment