Skip to content

Instantly share code, notes, and snippets.

@yongboy
Created January 31, 2012 08:56
Show Gist options
  • Save yongboy/1709539 to your computer and use it in GitHub Desktop.
Save yongboy/1709539 to your computer and use it in GitHub Desktop.
单线程版本,改变递增式获取结果的算法
package com.learn.jsry166y.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* 单线程版本,改变递增式获取结果的算法
* @author yongboy
* @time 2012-1-30
* @version 1.0
*/
public class ImprovedFibonacci {
private static final int[] resultsArray = { 1, 1, 2, 3, 5, 8, 13, 21, 34,
55, 89 };
public static final List<Long> results = new ArrayList<Long>();
static {
for (int i : resultsArray) {
results.add(Long.valueOf(i));
}
}
final int n;
ImprovedFibonacci(int n) {
this.n = n;
}
private long compute(int small) {
return results.get(small);
}
public Long compute() {
if (n <= resultsArray.length) {
return compute(n);
}
int index = -1;
while(n >= (index = results.size())){
results.add(compute(index - 2) + compute(index - 1));
}
return compute(index-1);
}
public static void main(String... args) throws InterruptedException,
ExecutionException {
long start = System.currentTimeMillis();
ImprovedFibonacci fjt = new ImprovedFibonacci(12);
System.out.println(fjt.compute());
System.out
.println("use time : " + (System.currentTimeMillis() - start));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment