package cn.xf.algorithm.ch02;
import java.util.Vector;
/**
* 斐波那契数列
* @author xiaof
*
*/
public class Fib {
/**
* 方式1,递归计算效率非常差双重指数级(不要问我怎么算的,我不会)
* 计算方法:百度=》带常系数的齐次二阶线性递推式
* @param n
* @return
*/
public static Long fib1(int n)
{
if(n <= 1)
return (long) n;
else
return fib1(n - 1) + fib1(n - 2);
}
public static Long fib2(int n)
{
Long f0 = 0l;
Long f1 = 1l;
// Long fibn = f1 + f2;
Long fibn = 0l;
for(int i = 2; i <= n; ++i)
{
fibn = f0 + f1;
f0 = f1;
f1 = fibn;
}
return fibn;
}
public static Vector<Long> fib3(int n)
{
Vector<Long> fib = new Vector<Long>();
fib.setSize(n + 1);
fib.set(0, 0l);
fib.set(1, 1l);
for(int i = 2; i <= n; ++i)
{
fib.set(i, fib.get(i - 1) + fib.get(i - 2));
}
return fib;
}
public static void main(String[] args) {
System.out.println(Fib.fib1(10));
System.out.println("******************************");
System.out.println(Fib.fib2(10));
System.out.println("******************************");
Vector<Long> result = Fib.fib3(10);
for(Long l : result)
{
System.out.print(l + "\t");
}
}
}