- import java.util.List;
- import java.util.ArrayList;
- /**
- * 斐波那契数列
- */
- public class Fibonacci {
- public static List<Integer> fibonacci(int size) throws Exception {
- int first = 0;
- int second = 1;
- List<Integer> result = new ArrayList<Integer> ();
- result.add(first);
- result.add(second);
- if(size < 0) {
- throw new Exception("Illegal argument!");
- }
- else if(size <= 2) {
- return result.subList(0, size);
- }
- int next;
- int count = 2; // 当前已经推导出的元素个数
- while(count++ < size) { // 基于fib(0)和fib(1)递推其他元素
- next = first + second;
- first = second;
- second = next;
- result.add(next);
- }
- return result;
- }
- public static void main(String[] args) throws Exception {
- List<Integer> fibArray = fibonacci(10);
- for(int i: fibArray) {
- System.out.print(i + "\\t");
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/020720149900.html
来源: http://www.codesnippet.cn/detail/020720149900.html