Skip to content

Instantly share code, notes, and snippets.

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